您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:树:Binary Tree Maximum Path Sum(124)

2016-08-26 15:37 465 查看
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

算法

求一棵二叉树上的最大路径。

直接 DFS 就可以了,返回以这一棵子树且一端在上的最大路径,然后维护一个最大路径就行了。

class Solution {
private:
int ret;
int dfs(TreeNode *root) {
if (root == NULL)
return 0;
int left_sum = max(0, dfs(root->left));
int right_sum = max(0, dfs(root->right));
ret = max(ret, left_sum + right_sum + root->val);
return max(left_sum, right_sum) + root->val;
}

public:
int maxPathSum(TreeNode *root) {
ret = INT_MIN;
dfs(root);
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: