LeetCode Solutions
124. Binary Tree Maximum Path Sum
Time: $O(n)$ Space: $O(h)$
class Solution {
public:
int maxPathSum(TreeNode* root) {
int ans = INT_MIN;
maxPathSumDownFrom(root, ans);
return ans;
}
private:
// root->val + 0/1 of its subtrees
int maxPathSumDownFrom(TreeNode* root, int& ans) {
if (root == nullptr)
return 0;
const int l = max(0, maxPathSumDownFrom(root->left, ans));
const int r = max(0, maxPathSumDownFrom(root->right, ans));
ans = max(ans, root->val + l + r);
return root->val + max(l, r);
}
};
class Solution {
public int maxPathSum(TreeNode root) {
maxPathSumDownFrom(root);
return ans;
}
private int ans = Integer.MIN_VALUE;
// root->val + 0/1 of its subtrees
private int maxPathSumDownFrom(TreeNode root) {
if (root == null)
return 0;
final int l = Math.max(maxPathSumDownFrom(root.left), 0);
final int r = Math.max(maxPathSumDownFrom(root.right), 0);
ans = Math.max(ans, root.val + l + r);
return root.val + Math.max(l, r);
}
}
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
ans = -math.inf
def maxPathSumDownFrom(root: Optional[TreeNode]) -> int:
nonlocal ans
if not root:
return 0
l = max(0, maxPathSumDownFrom(root.left))
r = max(0, maxPathSumDownFrom(root.right))
ans = max(ans, root.val + l + r)
return root.val + max(l, r)
maxPathSumDownFrom(root)
return ans