124. Binary Tree Maximum Path Sum
Difficulty: Hard
Topics: Tree, Depth-first Search
Similar Questions:
Problem:
Given a non-empty 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.
Example 1:
Input: [1,2,3] 1 / \ 2 3 Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42
Solutions:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
int maxPathToRoot;
return helper(root, maxPathToRoot);
}
int helper(TreeNode* root, int& maxPathToRoot) {
if (root == nullptr) {
maxPathToRoot = 0;
return 0;
}
int ret = INT_MIN;
int leftMaxPathToRoot = 0;
int rightMaxPathToRoot = 0;
if (root->left) {
ret = max(ret, helper(root->left, leftMaxPathToRoot));
}
if (root->right) {
ret = max(ret, helper(root->right, rightMaxPathToRoot));
}
maxPathToRoot = root->val + max(0, max(leftMaxPathToRoot, rightMaxPathToRoot));
return max(ret, root->val + max(0, leftMaxPathToRoot) + max(0, rightMaxPathToRoot));
}
};