Contact
Back to Home

Compute the sum of the maximum sum path that goes through the root in a tree.

Featured Answer

Question Analysis

The question is asking you to find the maximum sum path in a tree that passes through the root node. This is a common problem in tree-based data structures where you need to identify paths with the highest value of node sums. The path must start from the root, and you need to determine which combination of nodes from the root to any leaf (or another node) yields the maximum sum. This problem requires understanding tree traversal techniques such as Depth First Search (DFS) and might involve dynamic programming or recursion to keep track of the maximum path sum as you traverse the tree.

Answer

To solve this problem, we will use a recursive approach to explore all possible paths starting from the root and keep track of the maximum sum encountered. Below is a concise solution in Python:

class TreeNode:
    def __init__(self, value=0, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def maxSumPathThroughRoot(root):
    # Helper function to calculate maximum path sum
    def maxPathSum(node):
        if not node:
            return 0

        # Recursively find the maximum path sum of the left and right child
        left_sum = maxPathSum(node.left)
        right_sum = maxPathSum(node.right)

        # Calculate the maximum sum path that can be formed through this node
        max_single_path = max(node.value, node.value + max(left_sum, right_sum))

        # Update the overall maximum path sum that passes through the root
        max_path_through_root[0] = max(max_path_through_root[0], node.value + left_sum + right_sum)

        return max_single_path

    # Initialize the maximum path sum as negative infinity
    max_path_through_root = [float('-inf')]

    # Start the recursive function from the root node
    maxPathSum(root)

    return max_path_through_root[0]

# Example usage:
# Constructing a simple tree:
#       10
#      /  \
#     2    10
#    / \     \
#   20   1    -25
#             /  \
#            3    4

root = TreeNode(10)
root.left = TreeNode(2)
root.right = TreeNode(10)
root.left.left = TreeNode(20)
root.left.right = TreeNode(1)
root.right.right = TreeNode(-25)
root.right.right.left = TreeNode(3)
root.right.right.right = TreeNode(4)

print("Maximum sum path through root:", maxSumPathThroughRoot(root))

Explanation:

  • We define a helper function maxPathSum(node) that calculates the maximum path sum for each subtree.
  • For each node, calculate the path sum including the node itself, its left and right children.
  • Maintain a global variable max_path_through_root to store the maximum path sum encountered during traversal.
  • The function returns the maximum path sum through the root node of the tree.