以为自己修炼到家了,所以选了一道hard的题目,最后还是没做出来,纯粹参考其他人的代码。
代码真的很精简,有很多技巧,需要不断修炼。
题目:
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 does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
分析,最大值可能有二种情况。
2 possible choices1.Already calculated in left or right child
2.left max path + right max path + root
从下往上找。。。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//#define max(a,b) ((a)>(b))?(a):(b)
class Solution {
public:
int maxPathSum(TreeNode* root) {
dfs(root);
return ansmax;
}
private:
int ansmax=INT_MIN;
int dfs(TreeNode* root)
{
if(root==NULL) return 0;
int leftmax=dfs(root->left);
int rightmax=dfs(root->right);
if(leftmax+rightmax+root->val>ansmax) ansmax=leftmax+rightmax+root->val;
return max(0,root->val+max(leftmax,rightmax));//返回值一定是大于等于0的
}
};