LeetCode - 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.

Solution:

 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 ans = Integer.MIN_VALUE;
12     public int singleSide(TreeNode r) {
13         if(r == null) return 0;
14         int left = singleSide(r.left);
15         int right = singleSide(r.right);
16         int localMax = r.val;
17         if(left > 0)
18             localMax += left;
19         if(right > 0)
20             localMax += right;
21         if(localMax > ans) ans = localMax;
22         return r.val + Math.max(Math.max(0, left), right);
23     }
24     public int maxPathSum(TreeNode r) {
25         // Start typing your Java solution below
26         // DO NOT write main() function
27         ans = Integer.MIN_VALUE;//initialization
28         int tmp = singleSide(r);
29         //return Math.max(tmp, ans);
30         return ans;
31     }
32 }

 

posted @ 2013-01-25 15:39  cradle  阅读(649)  评论(0编辑  收藏  举报