Sunday, June 11, 2017

124. Binary Tree Maximum Path Sum

 public int maxPathSum(TreeNode root) {  
     int[] max=new int[1];  
     max[0]=Integer.MIN_VALUE;  
     helper(max,root);  
     return max[0];  
   }  
   public int helper(int[] max,TreeNode root){  
     if(root==null) return 0;  
     int leftMax=helper(max,root.left);  
     int rightMax=helper(max,root.right);  
     int localMax=Math.max(root.val,root.val+Math.max(leftMax,rightMax));  
     max[0]=Math.max(max[0],Math.max(localMax,root.val+leftMax+rightMax));  
     return localMax;  
   }  

No comments:

Post a Comment