Advertisement
sweet1cris

Untitled

Sep 25th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.74 KB | None | 0 0
  1. public class MaxPathSumBinaryTreeII {
  2.   public int maxPathSum(TreeNode root) {
  3.     // Assumptions: root is not null.
  4.     // max stores the global maximum path sum and will be
  5.     // updated during the recursion.
  6.     int[] max = new int[] { Integer.MIN_VALUE };
  7.     helper(root, max);
  8.     return max[0];
  9.   }
  10.  
  11.   // return the maximum path sum of the "single" path.
  12.   private int helper(TreeNode root, int[] max) {
  13.     if (root == null) {
  14.       return 0;
  15.     }
  16.     int left = helper(root.left, max);
  17.     int right = helper(root.right, max);
  18.     left = left < 0  0 : left;
  19.     right = right < 0  0 : right;
  20.     max[0] = Math.max(root.key + left + right, max[0]);
  21.     return root.key + Math.max(left, right);
  22.   }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement