您的位置:首页 > 其它

leetcode Binary Tree Maximum Path Sum

2016-09-09 09:46 302 查看
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
.

此题题意是:求二叉树中的一条和为最大的路径之和,该路径由有连接的节点组成,并不一定要root节点在路径中。
该路径有个特点,肯定是一个节点为最高层节点,路径的左段为该节点左孩子往下延伸的一条路径,右段为该节点右孩子往下延伸的一条路径。

采用递归的方法,先序处理二叉树,每访问到一个节点就计算以该节点为最高层节点往左右延伸的路径和,并在每次递归记录最大和。

代码如下:

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));//注意此返回值,是返回当前值、当前值加左孩子路径值或加右孩子路径值!!!
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode