Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
思路:
后续遍历,遇到负的就截掉。
class Solution {
public:
int maxPathSum(TreeNode *root) {
maxx = -2147483648;
postOrder(root);
return maxx;
}
private:
int maxx;
int postOrder(TreeNode *root){
if(!root)
return 0;
int l = postOrder(root->left);
int r = postOrder(root->right);
int v = max(l, r) + root->val;
maxx = max(maxx, l + r + root->val);
return max(v, 0);
}
};