输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
其实之前在学习平衡二叉树的时候就已经研究过这个问题了,平衡二叉树其子树的高度是其一个重要信息变量,两个子树的高度差是否超过1决定其是否要进行旋转调整,当时写的是:
- left == null ? 0 : left.height() 是求左子树的高度
- right == null ? 0 : right.height()是求右子树的高度
所以如上两个表达式取最大值,即为当前子树的高度
// 返回 以该结点为根结点的树的高度
public int height() {
return Math.max(left == null ? 0 : left.height(), right == null ? 0 : right.height()) + 1;
}
算了,我觉得蛮清晰的就懒得解释了,直接放完整版吧
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}