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.
Have you met this question in a real interview?
首先需要搞清楚一个子问题:给你一棵树,求从根到叶子的最大节点和,怎么求?
so easy,递归:
int f(TreeNode *root){
if(root==NULL)
return 0;
int l=f(root->left);
int r=f(root->right);
return max(max(l+root->val,r+root->val),root->val);
}
那么,在递归中求各个子树的经过根节点的路径和的最大值,即可。
- int maxnum=INT_MIN;
- int f(TreeNode *root){
- if(root==NULL)
- return 0;
- int l=f(root->left);
- int r=f(root->right);
- maxnum=max(max(l,0)+max(r,0)+root->val,maxnum);
- return max(max(l+root->val,r+root->val),root->val);
- }
- int maxPathSum(TreeNode *root) {
- if(root==NULL)
- return 0;
- f(root);
- return maxnum;
- }
<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(7) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
评论热议
本文介绍了一种寻找二叉树中最大路径和的算法。通过递归方式计算从根节点到叶子节点的最大和,并进一步拓展为计算任意两点间路径的最大和。
350

被折叠的 条评论
为什么被折叠?



