您的位置:首页 > 其它

Binary Tree Maximum Path Sum

2013-04-01 23:18 281 查看
Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:

Given the below binary tree,
1
/ \
2   3


Return
6
.
其实这个题目不难,但是我折腾了好久。
我第一次做这个题目的用了很直观的方法,对于每一个节点求取通过它的maxmum path sum,方法是用递归求深度,然后 left + root-> val + right
然后再遍历所有的节点,找到global maximum

这样做会很很多重复的计算导致大集合没过

但其实呢,在用递归求深度的时候就可以顺便把最终的结果求出来了,方法是设一个全局变量。

136ms过大集合~
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int ret;
public:
int depth(TreeNode *root){
if(!root) return 0;

int l = max(depth(root -> left), 0);
int r = max(depth(root -> right), 0);

int cur = l + r + root -> val;
ret = max(ret, cur);

return max(l, r) + root -> val;

}

int maxPathSum(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ret = INT_MIN;
depth(root);
return ret;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: