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.

 

 找出任意两个节点之间的路径,并且该路径的值之和最大。

PS:关键在于递归函数的返回值,应该返回该节点的任意子节点到该节点父节点之间路径的最大值,即root->l返回的值应该为root->l的任意子节点到root能得到的最大值-root->val。同时在遍历时时刻检查sum与max的大小并更新max的值。

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxPathSum(TreeNode *root) {
13         res=INT_MIN;
14         dfs(root);
15         return res;
16     }
17     
18     int dfs(TreeNode *root){
19         if(root==NULL){
20             return 0;
21         }
22         int sum=root->val;
23         
24         int l=dfs(root->left);
25         int r=dfs(root->right);
26         if(l>0) sum+=l;
27         if(r>0) sum+=r;
28         res=max(res,sum);
29         int tmp=max(l,r);
30         return tmp>0?tmp+root->val:root->val;
31     }
32     int res;
33 };

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值