Bird
Raised Fist0
Interview Prepchallenge-problemshardFacebookAmazonGoogleMicrosoft

Binary Tree Maximum Path Sum

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Steps
setup

Start at Root Node

We begin the recursion at the root node with value 1. The global max_sum is initialized to negative infinity.

💡 Initializing max_sum to -inf ensures any path sum will update it.
Line:def maxPathSum(root): max_sum = float('-inf') def helper(node):
💡 The algorithm starts with the root and prepares to explore all paths.
📊
Binary Tree Maximum Path Sum - Watch the Algorithm Execute, Step by Step
Watching the recursion unfold and how the algorithm chooses paths helps you understand the problem's complexity and the importance of ignoring negative gains.
Step 1/14
·Active fillAnswer cell
traverse
node
1
0
2
1
3
2
Result: "-inf"
traverse
1
0
node
2
1
3
2
Result: "-inf"
traverse
1
0
2
1
3
2
Result: "-inf"
traverse
1
0
2
1
3
2
Result: "-inf"
compare
1
0
node
2
1
3
2
Result: 2
move_right
1
0
node
2
1
3
2
Result: 2
traverse
1
0
2
1
node
3
2
Result: 2
traverse
1
0
2
1
3
2
Result: 2
traverse
1
0
2
1
3
2
Result: 2
compare
1
0
2
1
node
3
2
Result: 3
move_left
1
0
2
1
node
3
2
Result: 3
compare
node
1
0
2
1
3
2
Result: 6
move_left
node
1
0
2
1
3
2
Result: 6
record
1
0
2
1
3
2
Result: 6

Key Takeaways

The maximum path sum can include both left and right children of a node, not just a single path downwards.

This is hard to see from code alone because the return value only represents one path, but the global max_sum tracks combined paths.

Negative gains from children are ignored by taking max with 0, ensuring paths only add positive contributions.

This prevents paths with negative sums from reducing the overall maximum, a subtle but crucial insight.

The recursion explores the entire tree bottom-up, computing gains from leaves up to the root, updating max_sum at each node.

Seeing the recursion order and how gains propagate clarifies the algorithm's flow better than reading code.

Practice

(1/5)
1. You are given a binary tree and a target sum. The task is to find all root-to-leaf paths where the sum of the node values equals the target sum. Which algorithmic approach guarantees finding all such paths efficiently?
easy
A. Greedy traversal choosing the child with the closest value to the remaining sum
B. Depth-first search (DFS) with path tracking and backtracking to explore all root-to-leaf paths
C. Dynamic programming to store sums at each node and combine results bottom-up
D. Breadth-first search (BFS) with queue to find the shortest path matching the sum

Solution

  1. Step 1: Understand problem requires all root-to-leaf paths

    Since we must find all paths, not just one, exhaustive exploration is needed.
  2. Step 2: Identify DFS with path tracking and backtracking

    DFS explores each path fully, tracking the current path and sum, backtracking to explore alternatives.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    DFS explores all paths, greedy or BFS do not guarantee all paths [OK]
Hint: All root-to-leaf paths require exhaustive DFS [OK]
Common Mistakes:
  • Thinking greedy or BFS finds all paths
  • Confusing DP for path enumeration
2. What is the time complexity of the optimal DFS with two-value return solution for the House Robber III problem on a tree with n nodes?
medium
A. O(n^2) due to checking grandchildren nodes explicitly
B. O(n) but with extra O(n) space for memoization arrays
C. O(n) because each node is visited once in DFS
D. O(n log n) because of recursive calls and combining results

Solution

  1. Step 1: Identify DFS traversal cost

    The algorithm visits each node exactly once in a postorder DFS traversal.
  2. Step 2: Analyze operations per node

    At each node, constant time operations are done: combining left and right child results, no repeated work.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Linear traversal of n nodes -> O(n) time [OK]
Hint: DFS visits each node once, no repeated subproblems [OK]
Common Mistakes:
  • Assuming O(n^2) due to grandchildren checks
  • Confusing recursion stack space with time complexity
3. Examine the following buggy code for the Path Sum problem. Which line contains the subtle bug that causes incorrect results on some inputs?
def hasPathSum(root: Optional[TreeNode], targetSum: int) -> bool:
    def dfs(node, curr_sum):
        if not node:
            return False
        curr_sum += node.val
        if curr_sum == targetSum:  # Bug here
            return True
        return dfs(node.left, curr_sum) or dfs(node.right, curr_sum)
    return dfs(root, 0)
medium
A. Line 3: if not node: return False
B. Line 6: if curr_sum == targetSum:
C. Line 8: return dfs(node.left, curr_sum) or dfs(node.right, curr_sum)
D. Line 5: curr_sum += node.val

Solution

  1. Step 1: Understand leaf node condition

    The sum should be checked only at leaf nodes, not at every node.
  2. Step 2: Identify the bug

    Line 6 checks sum at any node, causing premature True returns for partial paths.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Bug causes incorrect True if partial path sum equals targetSum [OK]
Hint: Sum check must be at leaf nodes only [OK]
Common Mistakes:
  • Checking sum at internal nodes
  • Not handling null root
4. If the binary tree nodes can have parent pointers in addition to left and right children, which modification to the iterative one-stack postorder traversal algorithm can eliminate the need for the last_visited variable?
hard
A. Use the parent pointer to move back up after visiting a node's children, tracking traversal direction
B. Push nodes twice onto the stack to simulate postorder without tracking last visited
C. Perform a preorder traversal and reverse the output list at the end
D. Use two stacks: one for traversal and one for output, ignoring parent pointers

Solution

  1. Step 1: Understand role of last_visited

    Last_visited tracks if right child was processed to avoid revisiting; parent pointers can provide traversal direction.
  2. Step 2: Use parent pointer to detect traversal direction

    By moving up via parent pointer, algorithm knows if coming from left or right child, eliminating need for last_visited.
  3. Step 3: Compare other options

    Options B and D ignore parent pointers; A reverses preorder but does not leverage parent pointers; C uses parent pointers effectively.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Parent pointers enable direction-aware traversal without extra state [OK]
Hint: Parent pointers track traversal direction, removing last_visited [OK]
Common Mistakes:
  • Ignoring parent pointers
  • Using two stacks unnecessarily
  • Reversing preorder output without parent info
5. Suppose you want to extend the serialization/deserialization to support binary trees where nodes can have duplicate values and the tree can be very deep (height > 10,000). Which modification is necessary to ensure correctness and efficiency?
hard
A. Use iterative BFS serialization with null markers and iterative deserialization to avoid recursion stack overflow.
B. Use recursive DFS with memoization to handle duplicates and deep trees efficiently.
C. Switch to preorder traversal without null markers to reduce string size and recursion depth.
D. Serialize only unique node values and reconstruct tree assuming balanced shape.

Solution

  1. Step 1: Identify problem with deep recursion

    Recursive DFS can cause stack overflow on very deep trees.
  2. Step 2: Use iterative BFS with null markers

    Iterative BFS avoids recursion stack issues and null markers preserve structure even with duplicates.
  3. Step 3: Avoid assumptions about uniqueness or balanced shape

    Duplicates require storing all nodes explicitly; balanced assumptions break correctness.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Iterative BFS with null markers handles deep trees and duplicates safely [OK]
Hint: Iterative BFS avoids recursion limits and preserves structure [OK]
Common Mistakes:
  • Removing null markers to save space breaks reconstruction
  • Using recursion on deep trees causes stack overflow
  • Assuming unique values or balanced trees