Binary Tree Maximum Path Sum

1. Title

Binary Tree Maximum Path Sum

2. Http address

https://leetcode.com/problems/binary-tree-maximum-path-sum/

3. The question

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

Return 6.

4. My code(AC)

 1     //DFS res[0] = sub tree max; res[1] = from root max;
 2     public static int []  maxPathSumTwoHelp(TreeNode root){
 3         
 4         int res [] = new int[2];
 5         int res_left[];
 6         int res_right[];
 7         
 8         if( root.left != null && root.right != null)
 9         {
10             res_left = maxPathSumTwoHelp(root.left);
11             res_right = maxPathSumTwoHelp(root.right);
12             
13             res[1] = Math.max(res_left[1], res_right[1]) + root.val;
14             res[1] = Math.max(res[1], root.val);
15             res[0] = Math.max(res_left[0], res_right[0]);
16             res[0] = Math.max(res[0], res_left[1] + res_right[1] + root.val);
17             res[0] = Math.max(res[0], res[1]);
18             
19         }else{
20             if( root.left != null && root.right == null)
21             {
22                 res_left = maxPathSumTwoHelp(root.left);
23                 res[1] =  Math.max(res_left[1] + root.val, root.val);
24                 res[0] =  Math.max(res_left[0], root.val);
25                 res[0] =  Math.max(res[0], res[1]);
26             }else if( root.right != null &&  root.left == null)
27             {
28                 res_right = maxPathSumTwoHelp(root.right);
29                 res[1] =  Math.max(res_right[1] + root.val, root.val);
30                 res[0] =  Math.max(res_right[0], root.val);
31                 res[0] =  Math.max(res[0], res[1]);
32             }else{
33                 res[0] = root.val;
34                 res[1] = root.val;
35             }
36         }
37         return res;
38     }
39     // Accepted
40     public static int  maxPathSumTwo(TreeNode root){
41         if( root == null)
42             return 0;
43         int res[] = maxPathSumTwoHelp(root); 
44         return res[0];
45     }

 

posted @ 2015-11-16 20:33  ordi  阅读(126)  评论(0编辑  收藏  举报