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
.
/**
* 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 maxsum=INT_MIN;
int dfs(TreeNode* root)
{
if(root==NULL) return 0;
int left = dfs(root->left);
int right = dfs(root->right);
int sum = root->val;
if(left>0) sum+=left;
if(right>0) sum+= right;
maxsum = max(maxsum,sum);
return max(left,right)>0?max(left,right)+root->val:root->val;
}
int maxPathSum(TreeNode* root) {
dfs(root);
return maxsum;
}
};
分析:
此题中dfs返回的值并不是最终结果,只是单方向路径,而最终的最大和在遍历过程中被计算。
在dfs的过程中,以每个节点为中心计算一次sum,保存其最大值,计算sum的过程中需要左右路径的单方向求和,所以返回此单方向路径和。