此问题可拆解为求左右子树最高的高度加1,递归出口为访问到叶子节点本身时其高度为1,此时返回0即可。
class Solution{
public int height(TreeNode root){
if(root == null){
return 0;
}
return Math.max(height(root.left),height(root.right)) + 1;
}
}
由于使用了递归,内存开销巨大,不过不失为一种简单的方法求树高。