思路:經典的非遞歸層次遍歷:利用輔助隊列,先將頭節點入隊列,當隊列不空時出隊列的節點記爲 current,當current左節點不空時入隊列,其右節點不空時入隊列,如此循環即可。
求深度:構造變量cur記錄當前層訪問到的節點數,width記錄當前層的總個數,每當訪問過一層層數deep++;
此種方法同時可以求最大寬度,訪問第幾層的第幾個節點,是一種通用方法!
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null) return 0;
TreeNode current; //記錄當前節點
Queue<TreeNode> queue = new LinkedList<TreeNode>(); //構造輔助隊列
int cur,width; //cur記錄訪問到當前層的第幾個,widtd爲當前層的寬度
int deep=0; //初始深度爲0;
queue.offer(root); //頭結點入隊列
while(!queue.isEmpty()){ //隊列不空 循環記錄深度
cur=0; //新的一層cur賦爲0
width=queue.size(); //當前隊列裏的節點即爲該層的所有節點
while(cur<width){ //循環訪問該層的所有節點
current=queue.poll(); //訪問隊列的頭
if(current.left!=null) //左節點不空,左節點入隊列
queue.offer(current.left);
if(current.right!=null) //右節點不空,右節點入隊列
queue.offer(current.right);
cur++; //訪問完當前節點後cur++
}
deep++; //訪問完一層,層數++;
}
return deep;
}
}