Last active
August 5, 2017 01:27
-
-
Save cixuuz/c46bb7e67aebf2b3fb09b791409acf93 to your computer and use it in GitHub Desktop.
[124 Binary Tree Maximum Path Sum] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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