java 树 最大路径,求树的最大路径和

Problem: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.

这里所说的路径和是指从任意结点开始到任意结点结束的结点值之和,而且要注意的是结点的值也可能为负数。

思路:用递归思想,并用一个全局变量保存最大路径和的值。分别求当前结点的左子树和右子树的最大路径和,返回通过当前结点的最大路径和。并将下列四个值最大值与当前最大路径和比较,保证最大路径和始终是最大值。

当前结点值

当前结点值+左子树的最大路径和

当前结点值+右子树最大路径和

当前结点值+左子树最大路径和+右子树最大路径和

注意:这里在每次求通过一个结点的最大路径和时,不断更新整个树的最大路径和。

class Solution {

public:

int res;//保存最大路径和

int maxPathSum(TreeNode* root) {

res = -10000;

maxPathSumRe(root);

return res;

}

int maxPathSumRe(TreeNode* node)

{

if (node == NULL) return 0;

int l = maxPathSumRe(node->left);

int r = maxPathSumRe(node->right);

int maxSub = (l > r) ? l : r;

//sum用于保存通过当前结点的最大路径和

int sum = (node->val > maxSub + node->val) ? node->val : node->val + maxSub;

res = res > sum ? res : sum;

res = node->val + l + r > res ? node->val + l + r : res;

return sum;

}

};

http://www.dengb.com/Javabc/771559.htmlwww.dengb.comtruehttp://www.dengb.com/Javabc/771559.htmlTechArticleProblem: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. 这里所说的路径和是指从任意结点...

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值