題意
給定一個二叉樹,找出其最大深度。二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。說明: 葉子節點是指沒有子節點的節點。
示例
示例:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路
1- 節點判空,沒有就0深度
2- 判斷左右子樹的深度,找出最深的
3- 最深的長度+1(根節點)
解答
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int l = maxDepth(root.left);
int r = maxDepth(root.right);
return ( l > r ? l : r ) + 1;
}
}