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

LeetCode Binary Tree Maximum Path Sum

时间:2014-12-09 23:00:59      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11 int max = Integer.MIN_VALUE;
12     public int maxPathSum(TreeNode root) {
13         if (root == null) {
14             return 0;
15         }
16         maxSum(root);
17         return max;
18     }
19 
20     private int  maxSum(TreeNode root) {
21         if (root == null) {
22             return 0;
23         }
24         int leftSum=0;
25         int rightSum=0;
26         int val=root.val;
27         if (root.left != null) {
28             leftSum = maxSum(root.left);
29             if (leftSum > 0) {
30                 val = val + leftSum;
31             }
32         }
33 
34         if (root.right != null) {
35             rightSum = maxSum(root.right);
36             if (rightSum > 0) {
37                 val = val + rightSum;
38             }
39         }
40 
41         if (val > max) {
42             max = val;
43         }
44 
45         return Math.max(root.val, Math.max(root.val + leftSum, root.val + rightSum));
46 
47 
48     }
49 }

 

LeetCode Binary Tree Maximum Path Sum

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/birdhack/p/4154358.html

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