Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Last active August 24, 2019 05:59
Show Gist options
  • Save shixiaoyu/60f182ea40094ff4b4672b6622886147 to your computer and use it in GitHub Desktop.
Save shixiaoyu/60f182ea40094ff4b4672b6622886147 to your computer and use it in GitHub Desktop.
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