题目:二叉树的深度
思路
- 递归终止条件: 如果越过了叶子节点,节点为
null
,那么则返回0
; - 调用递归,求左子树的最大深度;
- 调用递归,求右子树的最大深度;
- 返回两者的最大值,由于还有根节点所以再
+1
;
代码
class Solution {
public int maxDepth(TreeNode root) {
//越过叶子节点
if(root == null){
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth,rightDepth) + 1;
}
}