104. Maximum Depth of Binary Tree
递归时,每层路径加一
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
3
/ \ +1
9 20
/ \ +1
15 7
\ + 1
null
求二叉树节点最远距离: 重点是这个公式max_dis = max(l_depth + r_depth, max(l_dis, r_dis))
,是说最远距离=max(左边最大深度+右边最大深度,max(左边最大距离,右边最大距离))
def maxDis(self, root):
return self.dfs(root)
def dfs(self, root):
if not root:
return [0, -1]
l_depth, l_dis = self.dfs(root.left)
r_depth, r_dis = self.dfs(root.right)
max_depth = max(l_depth, r_depth) + 1
max_dis = max(l_depth + r_depth, max(l_dis, r_dis))
return [max_depth, max_dis]
测试:
[3,9,20,null,null,15,7]
[1,2,3,4,5,6,7,8,null,null,null,null,9]
[1,2,null,3,4,5,null,null,6]
result:
[3,3]
[4,6]
[4,4]