124 Binary Tree Maximum Path Sum¶
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
For example: Given the below binary tree,
Return 6.
Idea:
Time complexity O(n) Space complexity O(h)
Solution: Recursion¶
// Runtime: 19 ms
class Solution {
public:
int maxPathSum(TreeNode* root) {
if (!root) return 0;
int ans = INT_MIN;
maxPathSum(root, ans);
return ans;
}
private:
int maxPathSum(TreeNode* root, int& ans) {
if (!root) return 0;
int l = max(0, maxPathSum(root->left, ans));
int r = max(0, maxPathSum(root->right, ans));
int sum = l + r + root->val;
ans = max(ans, sum);
return max(l, r) + root->val;
}
};
Related Problems:¶
-
- Longest Univalue Path
-
- Diameter of Binary Tree