本题可以有两种做法,最为常见的就是使用递归的方法。
解法1:递归常规做法,求出左右子树的高度,并进行比较,然后再加上根节点的高度1,并返回最终的结果!
public class Solution {
public int TreeDepth(TreeNode root) {
//特殊情况处理,如果为空,直接返回
if(root==null) return 0;
//求左子树的高度
int left_height = TreeDepth(root.left);
//求右子树的高度
int right_height = TreeDepth(root.right);
return (left_height>right_height)?(left_height+1):(right_height+1);
}
} 解法2:借助队列,并使用层次遍历二叉树,分别将每一层的节点放入到队列中,然后在遍历这些节点,再将他们的子节点放入队列,直到遍历到最后一层!
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null) return 0;
Queue<TreeNode> result = new LinkedList<>();
result.add(root);
int height = 0;
while(!result.isEmpty()){
//获取当前的根节点
int size = result.size();
while(size>0){//遍历当前层,将该层的子节点都加入队列中
TreeNode nowroot = result.poll();
if(nowroot.left!=null) result.add(nowroot.left);
if(nowroot.right!=null) result.add(nowroot.right);
size = size-1;//
}
height+=1;//高度加1
}
return height;
}
} 
京公网安备 11010502036488号