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 result; 12 public int maxPathSum(TreeNode root) { 13 result=Integer.MIN_VALUE; 14 dfs(root); 15 return result; 16 } 17 private int dfs(TreeNode root) { 18 // TODO Auto-generated method stub 19 if(root==null) 20 return 0; 21 int l=0; 22 int r=0; 23 if(root.left!=null) 24 l=dfs(root.left); 25 if(root.right!=null) 26 r=dfs(root.right); 27 int sum=root.val; 28 if(l>0) 29 sum+=l; 30 if(r>0) 31 sum+=r; 32 result=Math.max(result,sum); 33 return Math.max(0,Math.max(l,r))+root.val; //只能选择左边儿的或者右边儿的来组成一个path 34 } 35 }