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.
 1 public class Solution {
 2     public int maxPathSum(TreeNode root) {
 3         int res []={Integer.MIN_VALUE};
 4         helper(root,res);
 5         return res[0];
 6     }
 7     public int helper(TreeNode root,int[] res){
 8         if(root==null) return 0;
 9         int left = helper(root.left,res);
10         int right = helper(root.right,res);
11         int across = root.val+left+right;
12         int single = Math.max(root.val,Math.max(root.val+right,root.val+left));
13         res[0] = Math.max(res[0],Math.max(across,single));
14         return single;
15     }
16 }
View Code

 

posted @ 2014-02-17 01:46  krunning  阅读(166)  评论(0编辑  收藏  举报