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 parent4, continue up to the root10, and then step down the right branch through15to reach20.
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 isNone,12consumes slots3and4(5and18), and5consumes slots5and6(3and9). The route climbs from9through5up to12— their deepest shared ancestor — and steps down to18without ever climbing to root8.
Example 3
50
/ \
30 70
/ \
10 40
- Input:
tree = [50, 30, 70, 10, 40],a = 40,b = 50 - Output:
[40, 30, 50] - Explanation: Endpoint
50sits directly above40, so the route climbs straight up parent edges from40to30to50.
Constraints
0 <= len(tree) <= 10^4- Each non-
Noneelement oftreeis 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
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 valuesaandb. Our goal is to return the unique simple route (moving along parent-child edges without revisiting any node) starting ataand ending atb. 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 whereNonemarks a missing child. Unlike a binary-heap array, aNoneplaceholder 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
aandb: 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]whenais present. - Missing endpoint or empty tree: if
treeis[],[None], or eitheraorbdoes not appear in the tree, return[].
- Input
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
atobclimbs up parent edges fromato a meeting ancestor, then steps down child edges tob: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
aandb— the deepest node whose subtree contains bothaandb(counting a node as an ancestor of itself). Whenasits aboveb, the LCA isaitself and the upward leg is empty; whenbsits abovea(as in Example 3), the LCA isband the downward leg is empty. One unified algorithm handles every arrangement.Parse the level-order list into parent links
To climb upward from any node, we build a dictionary
parent_ofmapping each present node to its parent. We keyparent_ofby list index intree(0, 1, 2, ...) instead of node value:- Array indices are always non-negative, so
-1safely denotes "no parent" (the root) even when a node holds value0or-1. - Array indices remain unique even if duplicate node values are allowed in a follow-up.
We sweep
treeleft 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 (notNone), 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- Array indices are always non-negative, so
Locate both endpoints before climbing
Because
parent_ofstores only indices of real (non-None) nodes, iterating over its keys locates any target value inO(n)time. Verifying bothaandbupfront 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 -1Climb to the lowest common ancestor and stitch the route
With
start_idx(fora) andend_idx(forb) in hand, two iterativewhileloops find their meeting point — avoiding recursion completely so a 3,000-node skewed chain never hits Python's recursion limit:- Record
a's ancestor chain: Starting atstart_idx, followparent_ofuntil-1, inserting every visited index (includingstart_idx) into a setstart_ancestors. - Climb from
bto the first shared ancestor: Starting atend_idx, step upward whilecurr not in start_ancestors, appending each stepped-over index toreversed_down_leg. Since root index0belongs tostart_ancestors, this loop must terminate, and testingb's ancestors from deepest upward guarantees the first hitlca_idxis the LCA. - Stitch the output: Climb from
start_idxup tolca_idx(appending values), appendtree[lca_idx]once, and iterate overreversed(reversed_down_leg)to walk downward from belowlca_idxtoend_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- Record
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]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):
- Parsing the list assigns parent indices:
10(idx 0) is the root (-1),4(idx 1) and15(idx 2) have parent0,2(idx 3) and7(idx 4) have parent1, and20(idx 6) has parent2. - Climbing up from
7(idx 4) visits4 -> 1 -> 0, recordingstart_ancestors = {4, 1, 0}. - Climbing up from
20(idx 6) saves6, saves2, and then reaches0, which belongs tostart_ancestors— making index0(value10) the LCA. - 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)(andO(n)over real nodes). Constructingparent_ofpops at mostnindices from the queue and examines at most two list slots per present node before the queue or array ends. Locatingaandbchecks thenkeys ofparent_ofat most once each, and the ancestor climbs take at mosth + 1O(1)dictionary/set steps. In an unordered tree,O(n)is optimal because an endpoint value could sit anywhere. - Space:
O(n). Bothparent_ofand the queue hold at mostnindices, whilestart_ancestors,reversed_down_leg, andpathstore at mostO(h)(bounded byn) elements.
Edge cases
- Identical endpoints (
a == b):end_idxis already insidestart_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 (
aaboveb) or the downward leg (babovea, as in Example 3) empty with zero special-case branches. - Absent endpoint or empty tree (
[]or[None]): checkingstart_idx == -1 or end_idx == -1upfront returns[]cleanly. Noneslots followed by deeper levels:[8, None, 12, 5, 18, 3, 9]attaches5and18under12becauseNoneslots never enterwaiting_parents.- Zero and negative node values: indexing
parent_ofby array position (0, 1, ...) with-1for the root prevents node values0or-1from colliding with sentinels. - Deep skewed chains (e.g., 3,000 nodes): iterative
whileloops never touch the call stack.
Common mistakes
- Applying binary-heap index arithmetic (
2 * i + 1,2 * i + 2): compact breadth-first arrays omit children ofNoneentries, so heap formulas misalign every level beneath an internalNone. - 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 frombcollects nodes bottom-up, opposite to the downward direction from the LCA tob. - Using single-pass recursive LCA when endpoints can be missing: textbook recursive LCA returns
aimmediately upon encounteringawithout verifying thatbexists elsewhere in the tree. - Truthiness checks such as
if val:: a valid node holding0is falsy in Python and gets skipped if you testif val:instead ofif 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
awith acame_fromdictionary reachesbalong the unique route inO(n)time andO(n)space without explicitly finding the LCA. - Root-to-endpoint prefix stripping: record the root-to-
alist and root-to-blist, advance an index while both prefixes match to isolate their last shared node (the LCA), then join the reversed suffix ofa's list, the LCA, and the suffix ofb's list inO(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
aandbviaTreeNodeobject references or unique node IDs (such as array indices intree). Because ourparent_ofdictionary already keys nodes by list index rather than node value, acceptingstart_idxandend_idxdirectly 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 ofaand any copy ofbusing a multi-source BFS seeded with allaindices inO(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
aandbfromrootwithout 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 bothaandbare smaller thannode.val, step right whenever both are larger, and stop at the first split node where they diverge (or one equalsnode.val). That split node is the candidate LCA; from it, run two standard downward BST searches toaandbto 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
rootpointer, each downward pass descends one level per comparison, improving runtime fromO(n)toO(h)and memory fromO(n)toO(h)(storing only the output route of at most2h + 1values). On a balanced BST (h = O(log n)), that drops both bounds toO(log n), whereas a degenerate chain BST falls back toO(n)(and if the input were still passed as a flat level-order list rather than node pointers, deserializing the list would still costO(m)upfront).
Follow-up questions
- Suppose multiple nodes may store identical integer values — how must the endpoint representation and path-finding logic adapt?
- If the tree satisfies the Binary Search Tree (BST) ordering invariant and we are given a root pointer, what structural advantage do we gain?
- How would you write the step-by-step search procedure for that BST case, including checking whether both targets exist?
- How do the runtime and auxiliary memory bounds of the BST procedure compare with the unordered binary tree solution?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array