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
.
该路径有个特点,肯定是一个节点为最高层节点,路径的左段为该节点左孩子往下延伸的一条路径,右段为该节点右孩子往下延伸的一条路径。
采用递归的方法,先序处理二叉树,每访问到一个节点就计算以该节点为最高层节点往左右延伸的路径和,并在每次递归记录最大和。
代码如下:
class Solution {
private:
int maxval;
public:
int maxPathSum(TreeNode* root) {
if(root == NULL)
return 0;
maxval = INT_MIN;
maxsum(root);
return maxval;
}
int maxsum(TreeNode* root)
{
if(root == NULL)
return 0;
int val = root->val;
int left, right;
left = maxsum(root->left);//返回的是左孩子为最高节点的一条从上到下的路径
if(left>0)
val += left;
right = maxsum(root->right);//返回的是右孩子为最高节点的一条从上到下的路径
if(right>0)
val += right;
if(val > maxval)//每次递归都计算以该层计算节点为最高层节点的路径!!!
maxval = val;
return max(root->val, max(root->val+left, root->val+right));//注意此返回值,是返回当前值、当前值加左孩子路径值或加右孩子路径值!!!
}
};