题目
和求二叉树直径相同套路
Python
class Solution:
def __init__(self):
self.res = -inf
def maxPathSum(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
self.dfs(root)
return self.res
def dfs(self, root):
if not root:
return 0
left_depth = max(self.dfs(root.left), 0)
right_depth = max(self.dfs(root.right), 0)
self.res = max(self.res, left_depth + right_depth + root.val)
return root.val + max(left_depth, right_depth)
Java
class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return max;
}
public int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int leftMax = Math.max(dfs(root.left), 0);
int rightMax = Math.max(dfs(root.right), 0);
max = Math.max(max, root.val + leftMax + rightMax);
return root.val + Math.max(leftMax, rightMax);
}
}