Faaez Razeen

Binary Tree Maximum Path Sum

  • 2 min read
  • LC-Hard
  • Binary Tree

3 years ago

Solution

TimeSpaceExplanation
O(n)O(h)
def maxPathSum(self, root: Optional[TreeNode]) -> int: ans = root.val # This is important, if there's only one node in tree and that's negative, we need to return the root's value def dfs(root): nonlocal ans if root is None: return 0 # The max functions below take care of the cases where a child node has a negative return value left_max_path_sum = max(0, dfs(root.left)) right_max_path_sum = max(0, dfs(root.right)) ans = max(ans, root.val + left_max_path_sum + right_max_path_sum) return root.val + max(left_max_path_sum, right_max_path_sum) dfs(root) return ans