Complete the code to define the TreeNode class constructor.
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = [1] self.left = left self.right = right
The constructor sets the node's value to the given val parameter.
Complete the code to update the global maximum path sum inside the helper function.
def maxPathSum(root): max_sum = float('-inf') def helper(node): nonlocal max_sum if not node: return 0 left = max(helper(node.left), 0) right = max(helper(node.right), 0) max_sum = max(max_sum, node.val + left + [1]) return node.val + max(left, right) helper(root) return max_sum
The maximum path sum at the current node includes the node's value plus the left and right path sums. Here, we add right to node.val + left.
Fix the error in the return statement of the helper function to correctly return the max path sum for one side.
def helper(node): if not node: return 0 left = max(helper(node.left), 0) right = max(helper(node.right), 0) max_sum = max(max_sum, node.val + left + right) return node.val + [1]
The helper returns the node's value plus the maximum of left or right path sums because the path can only continue in one direction.
Fill both blanks to complete the maxPathSum function that uses a helper to find the maximum path sum.
def maxPathSum(root): max_sum = float('-inf') def helper(node): nonlocal max_sum if not node: return 0 left = max(helper(node.left), 0) right = max(helper(node.right), 0) max_sum = max(max_sum, node.val + left + right) return node.val + [1] return [2]
The helper returns node.val plus the maximum of left or right path sums. The main function returns the global max_sum found.
Fill all three blanks to complete the helper function that calculates max path sums and updates max_sum.
def maxPathSum(root): max_sum = float('-inf') def helper(node): nonlocal max_sum if not node: return 0 left = max(helper(node.left), 0) right = max(helper(node.right), 0) max_sum = max(max_sum, [1]) return [2] + max(left, right) return [3]
Update max_sum with node.val plus left and right sums. Return node.val plus max of left or right. Finally, return max_sum.
