Taro Logo

Binary Tree Maximum Path Sum

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+25
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
TreesRecursion

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node's values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.

Example 1:

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2:

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 104].
  • -1000 <= Node.val <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the tree node values be negative, and can the maximum path sum itself be negative if all nodes in the tree are negative?
  2. Does a 'path' have to start and end at different nodes, or can a valid path consist of a single node?
  3. Are there any structural guarantees on the binary tree, such as it being balanced, a complete binary tree, or skewed?
  4. What is the expected data type and range for the node values (e.g., standard 32-bit integers)?
  5. Is the input tree guaranteed to be non-empty, or do I need to handle a null root edge case?

Brute Force Solution

Approach

To find the maximum path sum in a tree using the brute force approach, you systematically examine every single possible path that connects any two nodes. By checking every combination of connected nodes, you calculate their total sum and keep track of the highest one found.

Here's how the algorithm would work step-by-step:

  1. Begin by identifying every possible path in the tree, remembering that a path is any unbroken sequence of connected nodes where you never visit the same node twice.
  2. Pick one of these paths to start your exploration.
  3. Add up all the values contained within the nodes of this chosen path.
  4. Compare this path sum against the highest sum you have found so far, and update your record if this new sum is larger.
  5. Repeat this process for every other possible path in the entire tree.
  6. Once you have checked every single path, your recorded highest sum will be your final answer.

Code Implementation

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


def max_path_sum_brute_force(root):
    if not root:
        return 0

    def collect_all_nodes(current_node, node_list):
        if not current_node:
            return
        node_list.append(current_node)
        collect_all_nodes(current_node.left, node_list)
        collect_all_nodes(current_node.right, node_list)

    def find_all_paths(current_node, adjacency_list, current_path, all_paths):
        current_path.append(current_node)
        all_paths.append(list(current_path))
        for neighbor in adjacency_list[current_node]:
            if neighbor not in current_path:
                find_all_paths(neighbor, adjacency_list, current_path, all_paths)
        current_path.pop()

    tree_nodes = []
    collect_all_nodes(root, tree_nodes)

    adjacency_list = {node: [] for node in tree_nodes}

    def build_graph(current_node):
        if not current_node:
            return
        if current_node.left:
            adjacency_list[current_node].append(current_node.left)
            adjacency_list[current_node.left].append(current_node)
            build_graph(current_node.left)
        if current_node.right:
            adjacency_list[current_node].append(current_node.right)
            adjacency_list[current_node.right].append(current_node)
            build_graph(current_node.right)

    build_graph(root)

    # Generate every single valid sequence of connected nodes because brute force requires checking all
    all_possible_paths = []
    for start_node in tree_nodes:
        find_all_paths(start_node, adjacency_list, [], all_possible_paths)

    maximum_sum_found = float('-inf')

    # Iterate through every path to compute its total sum and track the highest value encountered
    for path_sequence in all_possible_paths:
        current_path_sum = sum(node.val for node in path_sequence)
        if current_path_sum > maximum_sum_found:
            maximum_sum_found = current_path_sum

    # Return the highest sum discovered across all exhaustive path combinations
    return maximum_sum_found

Big(O) Analysis

Time Complexity
O(n²) – To find the maximum path sum using this brute force approach, we must examine every possible pair of nodes in a tree with n nodes to evaluate the path connecting them. For any given starting node, the number of potential endpoints scales linearly with n. Checking all unique paths requires exploring roughly n times n/2 combinations across the tree. Summing the work for all pairs leads to approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(H) – To find the maximum path sum using a recursive depth-first search approach, the auxiliary space is primarily consumed by the call stack frames. In the worst-case scenario where the binary tree is completely unbalanced and resembles a linked list, the recursion stack reaches a maximum depth of N, where N is the total number of nodes in the tree. Conversely, for a balanced binary tree, the maximum depth and therefore the stack space is proportional to the height of the tree, denoted as H or log N. Additionally, a constant amount of auxiliary memory is used for tracking the running global maximum sum across the recursive steps. Thus, the overall space complexity simplifies to O(N) in the worst case and O(log N) in the best case.

Optimal Solution

Approach

To find the most valuable continuous path through a branching tree of numbers, we can visit every junction and calculate the best possible score that can be made by combining the left and right paths. By passing the best single-side score upward while simultaneously checking if a complete peak path is formed at every point, we can find the absolute maximum score in a single pass.

Here's how the algorithm would work step-by-step:

  1. Imagine standing at the bottom-most parts of the tree and looking upward toward the main root.
  2. For any junction you visit, ask your left branch and your right branch for the maximum scoring path they can provide from their respective sides.
  3. Ignore any path from a branch that has a negative score, because adding a negative score would only drag down your total value.
  4. Calculate the total score of a potential mountain-shaped path that goes up through your left branch, passes through you as the peak, and goes down through your right branch.
  5. Compare this mountain-shaped path score against the highest score you have recorded so far across the entire tree, and update your record if this new one is higher.
  6. To help the junction directly above you, figure out which single side (either your left or your right, plus your own value) is better, and pass that single best score upward.
  7. Continue this process all the way up to the very top of the tree, ensuring every junction acts as a potential peak, until you are left with the highest recorded score overall.

Code Implementation

class Solution:
    def maxPathSum(self, root_node) -> int:
        maximum_path_sum = float('-inf')

        def calculate_gain(current_node):
            nonlocal maximum_path_sum
            if not current_node:
                return 0

            # Negative paths are ignored since they reduce the overall sum.
            left_branch_gain = max(calculate_gain(current_node.left), 0)
            right_branch_gain = max(calculate_gain(current_node.right), 0)

            # A peak path uses both left and right branches through current node.
            current_peak_path = current_node.val + left_branch_gain + right_branch_gain
            maximum_path_sum = max(maximum_path_sum, current_peak_path)

            # Only the best single side can be passed up to the parent junction.
            return current_node.val + max(left_branch_gain, right_branch_gain)

        calculate_gain(root_node)
        return maximum_path_sum

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of nodes in the binary tree, and the cost is driven by the recursive post-order traversal that visits every single node exactly once. At each junction, we perform a constant amount of work evaluating the left and right branch scores and updating the global maximum path sum. As the recursion propagates from the bottom-most leaves up to the root, we touch all n nodes in a single pass. This translates to executing a constant number of operations per node, which simplifies directly to O(n).
Space Complexity
O(H) – The space complexity is driven by the recursive function calls on the call stack as we traverse from the top of the tree down to the bottom-most junctions. In the worst-case scenario of a completely unbalanced tree, such as a linked list, the recursion depth reaches N, where N is the total number of nodes, requiring linear extra space. For a completely balanced tree, the maximum depth and thus the auxiliary stack space is proportional to the logarithm of N, denoted as O(log N). Therefore, the overall auxiliary space complexity depends directly on the height H of the tree.

Edge Cases

Null root pointer representing an empty tree
How to Handle:
Return zero or a special null sentinel value, though the problem states the tree is non-empty.
Binary tree with a single node containing a negative value
How to Handle:
The recursive DFS will return the negative value itself as the maximum path sum without adding child contributions.
Binary tree with all negative node values
How to Handle:
Initializing the global maximum to negative infinity ensures we correctly track the single least negative node.
Deeply skewed or degenerate binary tree resembling a linked list
How to Handle:
Recursion depth reaches N which may cause a stack overflow in languages without tail-call optimization.
Path that does not pass through the root node
How to Handle:
Computing the local maximum at every node allows any subtree to act as the turning point for a valid path.
Node values near the integer minimum or maximum boundaries
How to Handle:
Using standard integer types might cause arithmetic overflow when summing large paths, requiring careful constraint handling.
Paths where extending to a child yields a negative sum
How to Handle:
Taking the maximum of zero and the child path sum effectively discards unprofitable subtrees.
0/75 completed