Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 5, 2017 01:27
Show Gist options
  • Save cixuuz/c46bb7e67aebf2b3fb09b791409acf93 to your computer and use it in GitHub Desktop.
Save cixuuz/c46bb7e67aebf2b3fb09b791409acf93 to your computer and use it in GitHub Desktop.
[124 Binary Tree Maximum Path Sum] #leetcode
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPathDown(root);
return maxSum;
}
private int maxPathDown(TreeNode node) {
if (node == null) {
return 0;
}
int leftMax = Math.max(0, maxPathDown(node.left));
int rightMax = Math.max(0, maxPathDown(node.right));
maxSum = Math.max(maxSum, leftMax + rightMax + node.val);
return Math.max(leftMax, rightMax) + node.val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment