由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 讨论一道LeetCode题:Binary Tree Maximum Path Sum
相关主题
Leetcode bst max path-----is this solution correct?面试题总结(7) - Tree
Binary Tree Maximum Path Sumfb电话面试
问一个leetcode上面binary tree的题目感觉leetcode的OJ有点太偏重DP了
[leetcode] Maximum Depth of Binary Tree问一道google面经
help: leetcode "Recover Binary Search Tree" -- 附代码为啥有两个case不对??Binary Tree Maximum Path Sum
[leetcode] Minimum Depth of Binary Tree 我的这个答案说wrong answer,但是我在本地跑就是对的.请教大家一个问题:Maximum Height (Depth) of a Binary Tree Using PreOrder Traversal
这个题做的对吗?问道150上的题:sum of path in binary tree
Binary Tree Maximum Path Sum弱问:leetcode里Convert Sorted List to Binary Search Tree
相关话题的讨论汇总
话题: maxpath话题: maxsofar话题: result话题: int话题: root
进入JobHunting版参与讨论
1 (共1页)
n****r
发帖数: 120
1
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
这道题咋解呢?每个节点DFS?
b*****u
发帖数: 648
2
递归,有点tricky的地方在于递归函数每次返回的是最大的单侧路径,但同时把两侧加
自己的和与记录的最大值比较,最终返回的是那个记录值
class Solution {
public:
int maxPathSum(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int maxSoFar= root->val;
int tmp = maxContainRoot(root, maxSoFar);
return maxSoFar;
}
int maxContainRoot(TreeNode *root, int& maxSoFar)
{
if (root == NULL) return 0;
int leftMax = maxContainRoot(root->left,maxSoFar);
int rightMax = maxContainRoot(root->right,maxSoFar);
int result = root->val;
int maxPath = root->val;
int longerLeg = max(leftMax,rightMax);
result = max(result, result+longerLeg);

maxPath = max(maxPath,maxPath+leftMax);
maxPath = max(maxPath,maxPath+rightMax);
maxSoFar = max(maxSoFar, maxPath);

return result;
}
};
n****r
发帖数: 120
3
妙解!是比较tricky!多谢回复!学习了!
m*****k
发帖数: 731
4
>if (root == NULL) return 0;
this won't work when node value is negative,
and I believe you considered negative,
from this line result = max(result, result+longerLeg);
May I ask why need maxPath? isn't 'result' enough?
and no need to calc result+longerLeg, just check if longerLeg > 0 ,
b***m
发帖数: 5987
5
最近讨论过多次了。
1 (共1页)
进入JobHunting版参与讨论
相关主题
弱问:leetcode里Convert Sorted List to Binary Search Treehelp: leetcode "Recover Binary Search Tree" -- 附代码
check if a binary tree is a valid binary search tree[leetcode] Minimum Depth of Binary Tree 我的这个答案说wrong answer,但是我在本地跑就是对的.
Find the node with given value in binary tree in in-order这个题做的对吗?
leetcode Runtime error : Flatten Binary Tree to Linked ListBinary Tree Maximum Path Sum
Leetcode bst max path-----is this solution correct?面试题总结(7) - Tree
Binary Tree Maximum Path Sumfb电话面试
问一个leetcode上面binary tree的题目感觉leetcode的OJ有点太偏重DP了
[leetcode] Maximum Depth of Binary Tree问一道google面经
相关话题的讨论汇总
话题: maxpath话题: maxsofar话题: result话题: int话题: root