Created
June 20, 2021 12:24
-
-
Save vmarois/cb74eea8793983f6bd20c49d8b6c80e4 to your computer and use it in GitHub Desktop.
This file contains 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
class Solution: | |
def maxPathSum(self, root: TreeNode) -> int: | |
self.max_path_sum = float('-inf') # force update at least once | |
def recurse(root: TreeNode) -> int: | |
if not root: return 0 # base case | |
left_sum, right_sum = max(0, recurse(root.left)), max(0, recurse(root.right)) # only care about positive gains | |
self.max_path_sum = max(self.max_path_sum, left_sum + root.val + right_sum) | |
return root.val + max(left_sum, right_sum) | |
recurse(root) | |
return self.max_path_sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment