Last active
August 24, 2019 05:59
-
-
Save shixiaoyu/60f182ea40094ff4b4672b6622886147 to your computer and use it in GitHub Desktop.
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
private int max = Integer.MIN_VALUE; | |
public int maxPathSum(TreeNode root) { | |
maxPathSumHelper(root); | |
return this.max; | |
} | |
public int maxPathSumHelper(TreeNode root) { | |
if (root == null) { | |
return 0; | |
} | |
int left = maxPathSumHelper(root.left); | |
int right = maxPathSumHelper(root.right); | |
// the max on a single path | |
int singlePath = Math.max(root.val, Math.max(left, right) + root.val); | |
// max across the current node on two sides | |
int acrossPath = Math.max(singlePath, left + right + root.val); | |
if (acrossPath > this.max) { | |
this.max = acrossPath; | |
} | |
// Note: always want to return the single path for recursion, because you cannot include both path, else, | |
// it will not be a path | |
return singlePath; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment