您的位置:首页 > 其它

LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)

2015-10-28 19:56 337 查看
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
.

求二叉树的最大路径和,感觉好复杂,但是分析一下,由于中间的点不能重叠,所以说肯定一部分在某个点的左边一个在右边。所以可以遍历左右子树来求最大值,相当于遍历所有的单点以及其左右子树之后,不断的更新最大值,用ret全局变量来维护这个最大值。将总体当作根节点加上左边和右边就可以了,代码如下:

class Solution {
public:
int maxPathSum(TreeNode *root) {
if(!root) return ret;
ret = INT_MIN;
dfs(root);
return ret;
}

int dfs(TreeNode * node)
{
if(node == NULL) return 0;
int val = node->val;
int left = dfs(node->left);
int right = dfs(node->right);
if(left > 0) val += left;
if(right > 0) val += right;
if(val > ret)
ret = val;
return max(node->val, max(node->val + left, node->val + right));
}
private:
int ret;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: