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;
- }
相关热门文章
给主人留下些什么吧!~~
评论热议