//递归做法
public class Test38 {
public int TreeDepth(TreeNode root) {
//到达叶子的子节点,返回上一级,从0开始加
if (root==null){
return 0;
}
//递归左右子树
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
//从0开始加,每返回上一级就加一,比较左右子树,返回大的。
return Math.max(left,right)+1;
}
}
//思路二:利用树的层次搜索
public class Test38_2 {
public int TreeDepth(TreeNode root) {
if (root==null) return 0;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
//cur记录访问到当前层的第几个,widtd为当前层的宽度
int size;
int deep=0;
while (!queue.isEmpty()){
//定义每层的结点数
size = queue.size();
//层数增加的条件,当每层结点遍历完后,遍历下一层
for (int i=0;i<size;i++){
//root = 推出来的结点
root = queue.poll();
if (root.left!=null)queue.offer(root.left);
if (root.right!=null)queue.offer(root.right);
System.out.println(size+" ");
}
//遍历一层后,deep(深度)加一
deep++;
}
return deep;
}
}
原文:https://www.cnblogs.com/programmerzx/p/12353925.html