首页 > 代码库 > Binary Tree Maximum Path Sum 解题注意
Binary Tree Maximum Path Sum 解题注意
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.
解题思路,递归
a
b c
curmax = max (a+b, a, a+c) //计算当前节点单边最大值,
如果a+b 最大,那就是说,把左子树包含进来,有利可图
如果a+c 最大,把右子树包含进来,有利可图
如果 a,最大,那就到a为止,最好了。
gmax = max(gmax, max(curmax, a+b+c))
这个是看要不要抛弃前面的结果.
void maxpathsumhelper(TreeNode* root, int& currentsum, int& maxsum) { if(root == NULL)return; int leftsum = 0; int rightsum = 0; maxpathsumhelper(root->left,leftsum, maxsum); maxpathsumhelper(root->right,rightsum, maxsum); currentsum = max(root->val, max(root->val + leftsum, root->val + rightsum)); //this value will passedback maxsum = max(maxsum, max(currentsum, leftsum + rightsum + root->val)); } int maxPathSum(TreeNode *root) { if(root == NULL) return 0; int csum = INT_MIN; int maxsum = INT_MIN; maxpathsumhelper(root, csum, maxsum); return maxsum; }
Binary Tree Maximum Path Sum 解题注意
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。