首页 > 编程语言 > 详细

[Leetcode][JAVA] Binary Tree Maximum Path Sum

时间:2014-11-19 07:13:41      阅读:200      评论:0      收藏:0      [点我收藏+]

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.

 


对于树,我们可以找到其左右子树中终止于根节点的最大路径值,称为最大半路径值,如果都是正数,则可以把它们以及根节点值相加,如果其中有负数,则舍弃那一边的值(即置为零)。如此可以找到包含根节点的最大路径值。然后选择左右子树的最大半路径值中大的那个(负数则置为0)加上根节点的值作为新的最大半路径值传给父节点。

于是我们可以递归地考察每个子树,不断更新一个全局变量max。

基本情况为:子树为null,此时最大路径值应为0.

代码如下:

 1     int max;
 2     public int maxPathSum(TreeNode root) {
 3         max = root==null?0:root.val;
 4         findMax(root);
 5         return max;
 6     }
 7     public int findMax(TreeNode root) {
 8         if(root==null)
 9             return 0;
10         int left = Math.max(findMax(root.left),0);
11         int right = Math.max(findMax(root.right),0);
12         max = Math.max(max, left+right+root.val);
13         return Math.max(left, right) + root.val;
14     }

 

 

[Leetcode][JAVA] Binary Tree Maximum Path Sum

原文:http://www.cnblogs.com/splash/p/4107259.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!