Node-to-Node Route in a Binary Tree

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given a binary tree encoded as a compact level-order array tree (List[Optional[int]]) along with two integer values a and b. Implement find_path_between_nodes(tree, a, b) to compute the unique route connecting the node valued a to the node valued b, returning every visited node value in travel order from a through b (both endpoints included).

The input list tree uses standard breadth-first compact serialization: - Element 0 stores the root's integer value (if tree is empty or tree[0] is None, the tree contains no nodes). - Taking present (non-None) nodes from top to bottom and left to right, each present node claims the next two remaining entries in tree as its left child and right child. - An entry of None indicates an absent child and never consumes child positions further down the array. Trailing None placeholders at the end of tree may be omitted.

Every present node holds a distinct integer. Moving between adjacent nodes is allowed both upward (child to parent) and downward (parent to child), without revisiting any node: - When a == b and that value appears in tree, the route consists of the single element [a]. - One endpoint may lie directly above or below the other, in which case the route moves purely downward or purely upward. - Whenever the tree is empty or at least one of a or b does not appear anywhere in tree, return [].

Examples

Example 1

        10
       /  \
      4    15
     / \     \
    2   7     20
  • Input: tree = [10, 4, 15, 2, 7, None, 20], a = 7, b = 20
  • Output: [7, 4, 10, 15, 20]
  • Explanation: Starting at 7, we step up to its parent 4, continue up to the root 10, and then step down the right branch through 15 to reach 20.

Example 2

    8
     \
      12
     /  \
    5    18
   / \
  3   9
  • Input: tree = [8, None, 12, 5, 18, 3, 9], a = 9, b = 18
  • Output: [9, 5, 12, 18]
  • Explanation: Because 8's left child is None, 12 consumes slots 3 and 4 (5 and 18), and 5 consumes slots 5 and 6 (3 and 9). The route climbs from 9 through 5 up to 12 — their deepest shared ancestor — and steps down to 18 without ever climbing to root 8.

Example 3

        50
       /  \
      30   70
     /  \
    10  40
  • Input: tree = [50, 30, 70, 10, 40], a = 40, b = 50
  • Output: [40, 30, 50]
  • Explanation: Endpoint 50 sits directly above 40, so the route climbs straight up parent edges from 40 to 30 to 50.

Constraints

  • 0 <= len(tree) <= 10^4
  • Each non-None element of tree is an integer in [-10^9, 10^9], and all present node values are distinct.
  • -10^9 <= a, b <= 10^9
  • The tree height can be as large as the number of present nodes (for instance, a single skewed chain of several thousand nodes).

Step-by-step walkthrough

  1. Understand the input format and edge cases

    We receive a binary tree serialized as a compact level-order list tree (List[Optional[int]]) along with two endpoint values a and b. Our goal is to return the unique simple route (moving along parent-child edges without revisiting any node) starting at a and ending at b. Because trees are connected and acyclic, there is exactly one such route whenever both values exist.

    Make sure every boundary rule is crystal clear before writing code:

    • Input tree: compact breadth-first serialization where None marks a missing child. Unlike a binary-heap array, a None placeholder never claims child slots of its own further down the list:
    tree = [8, None, 12, 5, 18]
    
          8          index 0 (claims slots 1 and 2 -> None, 12)
           \
            12       index 2 (claims slots 3 and 4 -> 5, 18)
           /  \
          5    18    indices 3 and 4
    
    • Endpoints a and b: distinct integer node values in the base problem (the follow-up explores duplicate values).
    • Identical endpoints (a == b): the route begins and ends on the same node, returning [a] when a is present.
    • Missing endpoint or empty tree: if tree is [], [None], or either a or b does not appear in the tree, return [].
  2. Key idea: every tree route climbs to a turning point, then descends

    Picture the tree as a reporting hierarchy where every node except the root has a single parent. Any non-backtracking walk from a to b climbs up parent edges from a to a meeting ancestor, then steps down child edges to b:

              10         <-- lowest common ancestor (LCA) of 7 and 20
            /    \
           4     15      route from 7 to 20:
          / \      \     upward leg:   7 -> 4
         2   7     20    turning node: 10
                         downward leg: 15 -> 20
                         full route:   [7, 4, 10, 15, 20]
    

    That turning node is the lowest common ancestor (LCA) of a and b — the deepest node whose subtree contains both a and b (counting a node as an ancestor of itself). When a sits above b, the LCA is a itself and the upward leg is empty; when b sits above a (as in Example 3), the LCA is b and the downward leg is empty. One unified algorithm handles every arrangement.

  3. Parse the level-order list into parent links

    To climb upward from any node, we build a dictionary parent_of mapping each present node to its parent. We key parent_of by list index in tree (0, 1, 2, ...) instead of node value:

    • Array indices are always non-negative, so -1 safely denotes "no parent" (the root) even when a node holds value 0 or -1.
    • Array indices remain unique even if duplicate node values are allowed in a follow-up.

    We sweep tree left to right using a FIFO queue (deque) of present node indices waiting for their two child slots. Each popped index inspects the next two list positions; whenever a position holds an integer (not None), we record its parent and push its index onto the queue:

    tree:   [ 8, None, 12,  5, 18,  3,  9 ]
    index:    0    1    2   3   4   5   6
    
    pop 0 (val 8)  -> claims slots 1, 2 -> slot 1 is None (skipped!), parent_of[2]=0; queue=[2]
    pop 2 (val 12) -> claims slots 3, 4 -> parent_of[3]=2, parent_of[4]=2;            queue=[3, 4]
    pop 3 (val 5)  -> claims slots 5, 6 -> parent_of[5]=3, parent_of[6]=3;            queue=[4, 5, 6]
    

    Here is the helper function:

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def build_parent_index(tree: List[Optional[int]]) -> Dict[int, int]:
        """Map each real node's list index to its parent's list index (-1 for the root)."""
        if not tree or tree[0] is None:
            return {}
    
        # parent_of: {node_list_index: parent_list_index}; root at index 0 has parent -1
        parent_of: Dict[int, int] = {0: -1}
        # waiting_parents: FIFO queue of real node indices waiting to claim two child slots
        waiting_parents = deque([0])
        next_slot = 1
    
        while waiting_parents and next_slot < len(tree):
            parent_idx = waiting_parents.popleft()
            # Each present node consumes the next two slots (left child, then right child).
            # A None slot is an absent child and never enters waiting_parents, so it claims no slots.
            for _ in range(2):
                if next_slot < len(tree) and tree[next_slot] is not None:
                    parent_of[next_slot] = parent_idx
                    waiting_parents.append(next_slot)
                next_slot += 1
    
        return parent_of
    
  4. Locate both endpoints before climbing

    Because parent_of stores only indices of real (non-None) nodes, iterating over its keys locates any target value in O(n) time. Verifying both a and b upfront ensures that if either endpoint is missing, we return [] immediately rather than constructing a partial route.

    def find_node_index(
        tree: List[Optional[int]], parent_of: Dict[int, int], target: int
    ) -> int:
        """Return the list index of the real node holding `target`, or -1 if absent."""
        # Iterating over parent_of visits only real (non-None) nodes in level order.
        for idx in parent_of:
            if tree[idx] == target:
                return idx
        return -1
    
  5. Climb to the lowest common ancestor and stitch the route

    With start_idx (for a) and end_idx (for b) in hand, two iterative while loops find their meeting point — avoiding recursion completely so a 3,000-node skewed chain never hits Python's recursion limit:

    1. Record a's ancestor chain: Starting at start_idx, follow parent_of until -1, inserting every visited index (including start_idx) into a set start_ancestors.
    2. Climb from b to the first shared ancestor: Starting at end_idx, step upward while curr not in start_ancestors, appending each stepped-over index to reversed_down_leg. Since root index 0 belongs to start_ancestors, this loop must terminate, and testing b's ancestors from deepest upward guarantees the first hit lca_idx is the LCA.
    3. Stitch the output: Climb from start_idx up to lca_idx (appending values), append tree[lca_idx] once, and iterate over reversed(reversed_down_leg) to walk downward from below lca_idx to end_idx.
    def find_path_between_nodes(tree: List[Optional[int]], a: int, b: int) -> List[int]:
        # Phase 1: Parse the level-order list into parent links and locate both targets.
        parent_of = build_parent_index(tree)
        start_idx = find_node_index(tree, parent_of, a)
        end_idx = find_node_index(tree, parent_of, b)
        if start_idx == -1 or end_idx == -1:
            return []
    
        # Phase 2: Record every node index on the climb from `a` up to the root (including `a`).
        start_ancestors: Set[int] = set()
        curr = start_idx
        while curr != -1:
            start_ancestors.add(curr)
            curr = parent_of[curr]
    
        # Phase 3: Climb upward from `b` until hitting the first ancestor shared with `a`.
        # Because we test `b`'s ancestors from deepest to shallowest (and root 0 is in
        # start_ancestors), the first hit is guaranteed to be the lowest common ancestor (LCA).
        reversed_down_leg: List[int] = []
        curr = end_idx
        while curr not in start_ancestors:
            reversed_down_leg.append(curr)
            curr = parent_of[curr]
        lca_idx = curr
    
        # Phase 4: Stitch the path: climb from `a` up to LCA, add LCA once, then walk down to `b`.
        path: List[int] = []
        curr = start_idx
        while curr != lca_idx:
            val = tree[curr]
            assert val is not None
            path.append(val)
            curr = parent_of[curr]
    
        lca_val = tree[lca_idx]
        assert lca_val is not None
        path.append(lca_val)
    
        # reversed_down_leg was collected bottom-up (b -> ... -> child of LCA), so reverse it.
        for idx in reversed(reversed_down_leg):
            val = tree[idx]
            assert val is not None
            path.append(val)
    
        return path
    
  6. Walk through Example 2

    Let's trace tree = [8, None, 12, 5, 18, 3, 9], a = 9, b = 18:

    1. Locate endpoints:
       start_idx = 6 (tree[6] == 9)
       end_idx   = 4 (tree[4] == 18)
    
    2. Climb from start_idx = 6:
       6 -> parent_of[6] = 3 -> parent_of[3] = 2 -> parent_of[2] = 0 -> parent_of[0] = -1
       start_ancestors = {6, 3, 2, 0}
    
    3. Climb from end_idx = 4:
       curr = 4 (not in {6, 3, 2, 0}) -> reversed_down_leg = [4], curr = parent_of[4] = 2
       curr = 2 (in {6, 3, 2, 0}!)    -> stop; lca_idx = 2 (value 12)
    
    4. Stitch route:
       - Upward before LCA: curr = 6 -> append 9; curr = 3 -> append 5; next is 2 == lca_idx, stop
       - Turning point LCA: append tree[2] = 12
       - Downward after LCA: reversed([4]) gives [4] -> append tree[4] = 18
       - Result: [9, 5, 12, 18]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def build_parent_index(tree: List[Optional[int]]) -> Dict[int, int]:
        """Map each real node's list index to its parent's list index (-1 for the root)."""
        if not tree or tree[0] is None:
            return {}
    
        # parent_of: {node_list_index: parent_list_index}; root at index 0 has parent -1
        parent_of: Dict[int, int] = {0: -1}
        # waiting_parents: FIFO queue of real node indices waiting to claim two child slots
        waiting_parents = deque([0])
        next_slot = 1
    
        while waiting_parents and next_slot < len(tree):
            parent_idx = waiting_parents.popleft()
            # Each present node consumes the next two slots (left child, then right child).
            # A None slot is an absent child and never enters waiting_parents, so it claims no slots.
            for _ in range(2):
                if next_slot < len(tree) and tree[next_slot] is not None:
                    parent_of[next_slot] = parent_idx
                    waiting_parents.append(next_slot)
                next_slot += 1
    
        return parent_of
    
    
    def find_node_index(
        tree: List[Optional[int]], parent_of: Dict[int, int], target: int
    ) -> int:
        """Return the list index of the real node holding `target`, or -1 if absent."""
        # Iterating over parent_of visits only real (non-None) nodes in level order.
        for idx in parent_of:
            if tree[idx] == target:
                return idx
        return -1
    
    
    def find_path_between_nodes(tree: List[Optional[int]], a: int, b: int) -> List[int]:
        # Phase 1: Parse the level-order list into parent links and locate both targets.
        parent_of = build_parent_index(tree)
        start_idx = find_node_index(tree, parent_of, a)
        end_idx = find_node_index(tree, parent_of, b)
        if start_idx == -1 or end_idx == -1:
            return []
    
        # Phase 2: Record every node index on the climb from `a` up to the root (including `a`).
        start_ancestors: Set[int] = set()
        curr = start_idx
        while curr != -1:
            start_ancestors.add(curr)
            curr = parent_of[curr]
    
        # Phase 3: Climb upward from `b` until hitting the first ancestor shared with `a`.
        # Because we test `b`'s ancestors from deepest to shallowest (and root 0 is in
        # start_ancestors), the first hit is guaranteed to be the lowest common ancestor (LCA).
        reversed_down_leg: List[int] = []
        curr = end_idx
        while curr not in start_ancestors:
            reversed_down_leg.append(curr)
            curr = parent_of[curr]
        lca_idx = curr
    
        # Phase 4: Stitch the path: climb from `a` up to LCA, add LCA once, then walk down to `b`.
        path: List[int] = []
        curr = start_idx
        while curr != lca_idx:
            val = tree[curr]
            assert val is not None
            path.append(val)
            curr = parent_of[curr]
    
        lca_val = tree[lca_idx]
        assert lca_val is not None
        path.append(lca_val)
    
        # reversed_down_leg was collected bottom-up (b -> ... -> child of LCA), so reverse it.
        for idx in reversed(reversed_down_leg):
            val = tree[idx]
            assert val is not None
            path.append(val)
    
        return path
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine an organizational chart where every employee reports to one direct manager, and you want to route a memo along reporting lines from Dana to Omar. Because a tree contains no loops, every non-backtracking route shares the same structure: climb up from Dana through her chain of managers until hitting the first manager she shares with Omar, then walk down Omar's management chain to Omar. That deepest shared turning point is the lowest common ancestor (LCA) — the lowest node in the tree whose subtree includes both endpoints (counting a node as an ancestor of itself).

A naive attempt might compute child positions using binary-heap formulas (2 * i + 1 and 2 * i + 2), or launch a separate recursive search from every node. Heap index math breaks as soon as a None placeholder omits its children's positions in the compact level-order list (a top-to-bottom, left-to-right node sequence), repeated searches spend O(n^2) time, and deep recursion hits RecursionError on skewed chains past Python's 1,000-frame limit. Instead, we scan the level-order list once with a queue to record each node's parent index, then use iterative while loops to climb from both endpoints.

Here is a quick trace on Example 1 (tree = [10, 4, 15, 2, 7, None, 20], a = 7, b = 20):

  1. Parsing the list assigns parent indices: 10 (idx 0) is the root (-1), 4 (idx 1) and 15 (idx 2) have parent 0, 2 (idx 3) and 7 (idx 4) have parent 1, and 20 (idx 6) has parent 2.
  2. Climbing up from 7 (idx 4) visits 4 -> 1 -> 0, recording start_ancestors = {4, 1, 0}.
  3. Climbing up from 20 (idx 6) saves 6, saves 2, and then reaches 0, which belongs to start_ancestors — making index 0 (value 10) the LCA.
  4. Combining the upward leg ([7, 4]), the LCA ([10]), and the reversed downward leg ([15, 20]) yields [7, 4, 10, 15, 20].

Complexity

Let m be the length of tree, n be the count of present (non-None) nodes (n <= m), and h be the tree height (h < n when n >= 1).

  • Time: O(m) (and O(n) over real nodes). Constructing parent_of pops at most n indices from the queue and examines at most two list slots per present node before the queue or array ends. Locating a and b checks the n keys of parent_of at most once each, and the ancestor climbs take at most h + 1 O(1) dictionary/set steps. In an unordered tree, O(n) is optimal because an endpoint value could sit anywhere.
  • Space: O(n). Both parent_of and the queue hold at most n indices, while start_ancestors, reversed_down_leg, and path store at most O(h) (bounded by n) elements.

Edge cases

  • Identical endpoints (a == b): end_idx is already inside start_ancestors, leaving both legs empty so the LCA alone produces [a].
  • Ancestor-descendant pair: the LCA equals the higher endpoint, leaving either the upward leg (a above b) or the downward leg (b above a, as in Example 3) empty with zero special-case branches.
  • Absent endpoint or empty tree ([] or [None]): checking start_idx == -1 or end_idx == -1 upfront returns [] cleanly.
  • None slots followed by deeper levels: [8, None, 12, 5, 18, 3, 9] attaches 5 and 18 under 12 because None slots never enter waiting_parents.
  • Zero and negative node values: indexing parent_of by array position (0, 1, ...) with -1 for the root prevents node values 0 or -1 from colliding with sentinels.
  • Deep skewed chains (e.g., 3,000 nodes): iterative while loops never touch the call stack.

Common mistakes

  • Applying binary-heap index arithmetic (2 * i + 1, 2 * i + 2): compact breadth-first arrays omit children of None entries, so heap formulas misalign every level beneath an internal None.
  • Listing the LCA twice: concatenating [a, ..., LCA] with [LCA, ..., b] without dropping one copy duplicates the turning node.
  • Forgetting to reverse the b-to-LCA climb: walking upward from b collects nodes bottom-up, opposite to the downward direction from the LCA to b.
  • Using single-pass recursive LCA when endpoints can be missing: textbook recursive LCA returns a immediately upon encountering a without verifying that b exists elsewhere in the tree.
  • Truthiness checks such as if val:: a valid node holding 0 is falsy in Python and gets skipped if you test if val: instead of if val is not None:.

Alternative approaches

  • Breadth-first search (BFS) on an undirected adjacency map: breadth-first search (BFS) explores a graph one hop layer at a time with a queue. Treating each parent-child link as bidirectional and running BFS from a with a came_from dictionary reaches b along the unique route in O(n) time and O(n) space without explicitly finding the LCA.
  • Root-to-endpoint prefix stripping: record the root-to-a list and root-to-b list, advance an index while both prefixes match to isolate their last shared node (the LCA), then join the reversed suffix of a's list, the LCA, and the suffix of b's list in O(n) time and space.

Follow-up questions

  • Suppose multiple nodes may store identical integer values — how must the endpoint representation and path-finding logic adapt? Once values can repeat, a bare integer no longer pinpoints a unique node, so the caller must identify a and b via TreeNode object references or unique node IDs (such as array indices in tree). Because our parent_of dictionary already keys nodes by list index rather than node value, accepting start_idx and end_idx directly leaves the entire LCA climb unchanged! If the signature had to remain value-based, you would first agree on a disambiguation rule — such as finding a shortest route between any copy of a and any copy of b using a multi-source BFS seeded with all a indices in O(n) time.
  • If the tree satisfies the Binary Search Tree (BST) ordering invariant and we are given a root pointer, what structural advantage do we gain? A Binary Search Tree (BST) keeps distinct keys ordered so every key in a node's left subtree is strictly smaller than the node's key and every key in its right subtree is strictly larger. That ordering acts like a signpost at every node, letting us steer directly toward a and b from root without building parent links or scanning unrelated subtrees.
  • How would you write the step-by-step search procedure for that BST case, including checking whether both targets exist? Starting at root, step left whenever both a and b are smaller than node.val, step right whenever both are larger, and stop at the first split node where they diverge (or one equals node.val). That split node is the candidate LCA; from it, run two standard downward BST searches to a and b to collect both legs and confirm neither target is missing:
def path_down_bst(node, target):
    path = []
    while node is not None:
        path.append(node.val)
        if target == node.val:
            return path
        node = node.left if target < node.val else node.right
    return None  # target is absent from the BST


def bst_path(root, a, b):
    node = root
    while node is not None:
        if a < node.val and b < node.val:
            node = node.left
        elif a > node.val and b > node.val:
            node = node.right
        else:
            break
    if node is None:
        return []
    up_leg = path_down_bst(node, a)
    down_leg = path_down_bst(node, b)
    if up_leg is None or down_leg is None:
        return []
    up_leg.reverse()
    return up_leg + down_leg[1:]
  • How do the runtime and auxiliary memory bounds of the BST procedure compare with the unordered binary tree solution? Given a root pointer, each downward pass descends one level per comparison, improving runtime from O(n) to O(h) and memory from O(n) to O(h) (storing only the output route of at most 2h + 1 values). On a balanced BST (h = O(log n)), that drops both bounds to O(log n), whereas a degenerate chain BST falls back to O(n) (and if the input were still passed as a flat level-order list rather than node pointers, deserializing the list would still cost O(m) upfront).

Follow-up questions

Similar questions

More Ripple interview questions

All 1 Ripple questions →