码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-124 Binary Tree Maximum Path Sum

时间:2015-03-19 12:58:48      阅读:116      评论: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.

 

题意: 求一个二叉树中任意联通两点路径和的最大值。 

思路: 深度遍历该二叉树。

具有最大和的路径有三种情况:

1. 就在root.left子树中;2. 就在root.right子树中;3.包含root节点,一部分在root.left中,另一部分在root.right中。

我们记录两个数据,全局变量max表示全局的最大值,局部变量currentMax表示经过当前root节点的路径的最大值。如下图所示

技术分享

在以-9为根的子树中,max=7, currentMax=(-9+7)=-2;

在以3为根节点的子树中,max=11,currentMax=(6+3)=9;

在以1为根节点的子树中,max=11, currentMax=(1+9)=10;

最后,我们想要的结果是max;

本题需要注意递归方法的返回值。代码如下:

 1 public int maxPathSum(TreeNode root) {
 2         if(root == null)
 3             return 0;
 4         maxPathSumHelper(root);
 5         return this.max;
 6     }
 7     
 8     public int max = Integer.MIN_VALUE;
 9     public int maxPathSumHelper(TreeNode root) {
10         if(root == null)
11             return 0;
12         int leftMax = 0;
13         int rightMax = 0;
14         
15         int returnValue = root.val;
16         max = Math.max(root.val, max);
17         if(root.left != null) {
18             leftMax = maxPathSumHelper(root.left);
19             max = Math.max(max, Math.max(leftMax, leftMax+root.val));
20             returnValue = Math.max(returnValue, leftMax+root.val);
21         }
22         if(root.right != null) {
23             rightMax = maxPathSumHelper(root.right);
24             max = Math.max(max, Math.max(rightMax, rightMax+root.val));
25             returnValue = Math.max(returnValue, rightMax+root.val);
26         }
27         if(root.left != null && root.right != null) {
28             max = Math.max(max,  root.val+leftMax+rightMax);
29         }
30         
31         return returnValue;
32     }

 

LeetCode-124 Binary Tree Maximum Path Sum

标签:

原文地址:http://www.cnblogs.com/linxiong/p/4350002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!