[leetCode]Binary Tree Maximum Path Sum
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
.
思想主要是使用递归,获得节点左枝和右枝的最大值,然后和自己的值相加,如果大于最大值则替换。
同时要注意的是:如果该节点有父节点,那么只能返回self.val+left.val或者self.val+right.val.
详细参考:http://www.cnblogs.com/shawnhue/archive/2013/06/08/leetcode_124.html
C++代码
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxSum; bool hasParent; Solution(){ maxSum = -999;} int maxPathSum(TreeNode *root) { maxNodeSum(root,false); return maxSum; } private: int maxNodeSum(TreeNode *root, bool hsaParent){ int leftSum,rightSum,curmax; leftSum = rightSum = curmax = 0; TreeNode *cur = root; if(cur == NULL) return 0; if(cur->left != NULL) leftSum = maxNodeSum(cur->left,true); if(cur->right != NULL) rightSum = maxNodeSum(cur->right,true); if(leftSum < 0) leftSum = 0; if(rightSum < 0) rightSum = 0; curmax = cur->val+leftSum+rightSum; if(maxSum < curmax) maxSum = curmax; if(hasParent) curmax = cur->val + ((leftSum > rightSum)?leftSum : rightSum); return curmax; } };
艰难的成长