Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 25, 2015 20:46
Show Gist options
  • Save dmnugent80/9af87a6659221960f6c0 to your computer and use it in GitHub Desktop.
Save dmnugent80/9af87a6659221960f6c0 to your computer and use it in GitHub Desktop.
Binary Tree Maximum Sum Path
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null) return root.val;
int[] max = {Integer.MIN_VALUE};
maxPathSumHelper(root, max);
return max[0];
}
public int maxPathSumHelper(TreeNode node, int[] max) {
if (node == null) return Integer.MIN_VALUE;
int left = maxPathSumHelper(node.left, max);
int right = maxPathSumHelper(node.right, max);
left = left > 0 ? left : 0;
right = right > 0 ? right : 0;
if (node.val + left + right > max[0]) {
max[0] = node.val + left + right;
}
return node.val + Math.max(left, right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment