Key-Aligned Merge of Two Rooted N-ary Trees
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given two rooted n-ary trees tree1 and tree2 whose nodes carry integer keys, fuse them together along aligned key paths and return the merged tree in canonical preorder format:
def merge_trees_by_key(tree1: list[list[int]], tree2: list[list[int]]) -> list[list[int]]:
Representation & Merge Rules
- Input table format: An empty list
[]represents an empty tree. Otherwise, entryiis[key, parent]: entry0is the root withparent = -1, and every entryi >= 1has0 <= parent < ireferencing its parent's index in that same input list. Siblings under the same parent are ordered by ascending input index. - Empty inputs & mismatched roots:
- If both
tree1andtree2are empty, return[]. - If one input is empty, return the non-empty tree serialized in the preorder output format below.
- If both inputs are non-empty and their root keys differ (
tree1[0][0] != tree2[0][0]), no merge is possible: return[].
- If both
- Aligned fusion: Node
ufromtree1and nodevfromtree2fuse into one output node if and only ifuandvshare the exact same key and stand at aligned positions (both are roots, or their respective parents fused with each other). Any node lacking an aligned same-key partner in the other tree is copied over intact together with its entire subtree (preserving its original sibling ordering). - Child ordering under a fused node: When
u(fromtree1) andv(fromtree2) fuse, their merged node retains their common key and orders its direct children as follows:- First, each child of
uinu's original child order — recursively fused withv's child of the same key if present, or copied intact with its subtree otherwise. - Next, each child of
vwhose key does not occur amongu's children, inv's original child order, copied intact with its subtree.
- First, each child of
- Preorder output format: Emit nodes in depth-first preorder (visit a node first, then completely emit each child's subtree in the child order defined above). Each output entry is
[key, parent_idx], whereparent_idxis-1for the root and the parent's index in the returned output list for all other nodes.
Examples
Example 1
Input:
tree1 = [[10, -1], [20, 0], [30, 0], [25, 1]]
tree2 = [[10, -1], [30, 0], [40, 0], [35, 1], [45, 2]]
Output:
[[10, -1], [20, 0], [25, 1], [30, 0], [35, 3], [40, 0], [45, 5]]
Walk-through: Both roots carry key 10 and fuse at output index 0. Under 10, tree1's children come first: 20 (unmatched, copied with its child 25), followed by 30 (fused with tree2's 30, gaining child 35). Finally, tree2's unmatched child 40 is appended along with its child 45, yielding preorder 10, 20, 25, 30, 35, 40, 45.
Example 2
Input:
tree1 = [[10, -1], [50, 0]]
tree2 = [[20, -1], [50, 0]]
Output:
[]
Walk-through: Root keys 10 and 20 do not match, so the trees cannot fuse even though both contain a child with key 50.
Example 3
Input:
tree1 = [[7, -1], [9, 0], [4, 0], [9, 2]]
tree2 = [[7, -1], [4, 0], [9, 0], [6, 1], [9, 1]]
Output:
[[7, -1], [9, 0], [4, 0], [9, 2], [6, 2]]
Walk-through: Root 7 orders its children according to tree1 (9, then 4), fusing both with their counterparts in tree2. Under fused node 4, tree1's child 9 comes first (fusing with tree2's 9 under 4), followed by tree2's unmatched child 6. Key 9 appears at two depths, and each instance only fuses with a 9 under the same fused parent.
Constraints
0 <= len(tree1) <= 10^4and0 <= len(tree2) <= 10^4-10^9 <= key <= 10^9- In any non-empty input, entry
0hasparent == -1, and every entryi >= 1satisfies0 <= parent < i. - Within each tree, all direct children of any single parent have distinct keys (identical keys may still occur under different parents or depths).
- Every root-to-leaf path in either input contains at most
500nodes.
Step-by-step walkthrough
Understand the input and output encoding
An n-ary tree is a rooted tree where each node can have any number of children (
0, 1, 2, ...). Instead of node objects with pointers, this problem gives each tree as a flat table of[key, parent_row]rows:- Row
0is always the root, withparent_row = -1. - Every later row
ipoints to an earlier row0 <= parent_row < ias its parent. - A node's children are ordered by increasing row index.
Watch out for a subtle detail: the input rows are not necessarily in preorder (visiting a node first, then completely finishing its first child's subtree before starting its second child). Look at
tree1from Example 1:Input tree1: [[10, -1], [20, 0], [30, 0], [25, 1]] Row 0: key 10 (root) / \ Row 1: key 20 Row 2: key 30 | Row 3: key 25 Input row order (breadth-first): 10 (row 0), 20 (row 1), 30 (row 2), 25 (row 3) Required output order (preorder): 10 (row 0), 20 (row 1), 25 (row 2), 30 (row 3)Notice that even if
tree2were empty, we could not returntree1unchanged: in preorder, key25moves to row2and key30moves to row3! That means we always build fresh output rows with newly assigned parent indices.- Row
Convert parent pointers into child lists
Each input row tells a child who its parent is (pointing upward), whereas merging starts at the roots and walks downward to children. Before merging, we build a downward child list
children[i]for every nodei.Because we scan
row_idxfrom1up tolen(tree) - 1in increasing order, appendingrow_idxtochildren[parent_idx]automatically keeps every node's children sorted by increasing input row index.def build_children(tree: list[list[int]]) -> list[list[int]]: """Return adjacency lists where children[i] holds node i's child row indices in order.""" node_count = len(tree) # children[i]: list of child row indices of node i, e.g. [[1, 2], [3], [], []] children: list[list[int]] = [[] for _ in range(node_count)] # Scanning rows 1..node_count-1 in order keeps each parent's children ordered by row index. for row_idx in range(1, node_count): parent_idx = tree[row_idx][1] children[parent_idx].append(row_idx) return childrenThis single pass takes
O(n)time andO(n)space for ann-node tree.Key idea: walk matched pairs together and index sibling keys
Two nodes are combined only when they have the same key and sit at matching positions (both are roots, or their parents were combined). A node with key
9under parent4never combines with a key9directly under root7.Here is how Example 1 combines
tree1andtree2:tree1 tree2 merged tree 10 10 10 / \ / \ / | \ 20 30 30 40 20 30 40 | | | | | | 25 35 45 25 35 45 (only 1) (30 matches!) (only 2) (tree1 order first, then 40 from tree2)When
node1(intree1) andnode2(intree2) are combined:- Walk
node1's children intree1's order. Ifnode2has a child with the same key, recursively combine those two children; otherwise copynode1's child and its whole subtree. - Walk
node2's children intree2's order. For any child whose key did not appear amongnode1's children, copy that child and its whole subtree.
How do we check whether
node2has a child withchild1_key? Scanningchildren2[node2]linearly for every child ofnode1would takedeg(node1) * deg(node2)steps — up to10^4 * 10^4 = 10^8comparisons when two roots each have10,000children! Because sibling keys under any single parent are guaranteed distinct, we first putnode2's children into a dictionarytree2_child_by_key = {key: child2_idx}so each lookup takesO(1)average time.- Walk
Emit preorder rows on the fly as we recurse
We do not need to build intermediate tree objects and then flatten them in a second pass. A recursive function that appends the current node first and then visits each child in order naturally visits nodes in exact preorder!
Whenever we append a node to
merged_rows, its index in the output iscurrent_out_idx = len(merged_rows)right before appending. Passingcurrent_out_idxdown to each recursive child call gives every child its exactparent_out_idx.For an unmatched node whose entire subtree comes from just one tree,
copy_subtreewrites the node and recursively copies its children in their original order:def copy_subtree( tree: list[list[int]], children: list[list[int]], node_idx: int, parent_out_idx: int, ) -> None: # Record this node's output position right before appending it, so children can point to it. current_out_idx = len(merged_rows) node_key = tree[node_idx][0] merged_rows.append([node_key, parent_out_idx]) for child_idx in children[node_idx]: copy_subtree(tree, children, child_idx, current_out_idx)Because every root-to-leaf path has at most
500nodes, recursion uses at most500stack frames, safely within Python's default limit of1,000.Combine two matched nodes in the required child order
merge_nodes(node1_idx, node2_idx, parent_out_idx)emits the combined node, indexesnode2's children by key, processesnode1's children first (recording their keys intree1_child_keys), and finally appendsnode2's unmatched children.At the top level of
merge_trees_by_key: - If both trees are non-empty andtree1[0][0] != tree2[0][0], return[]immediately. - If both are non-empty (so root keys match), callmerge_nodes(0, 0, -1). - If only one tree is non-empty, callcopy_subtree(..., 0, -1)to re-encode it in preorder. - If both are empty,merged_rowsremains[].def merge_nodes(node1_idx: int, node2_idx: int, parent_out_idx: int) -> None: current_out_idx = len(merged_rows) shared_key = tree1[node1_idx][0] merged_rows.append([shared_key, parent_out_idx]) # tree2_child_by_key: {child_key: child_row_idx} for node2's children. # Sibling keys within one tree are distinct, so each key maps to at most one child. tree2_child_by_key: dict[int, int] = {} for child2_idx in children2[node2_idx]: child2_key = tree2[child2_idx][0] tree2_child_by_key[child2_key] = child2_idx # Rule 1: Visit node1's children in node1's order; merge matches, copy non-matches. tree1_child_keys: set[int] = set() for child1_idx in children1[node1_idx]: child1_key = tree1[child1_idx][0] tree1_child_keys.add(child1_key) if child1_key in tree2_child_by_key: merge_nodes(child1_idx, tree2_child_by_key[child1_key], current_out_idx) else: copy_subtree(tree1, children1, child1_idx, current_out_idx) # Rule 2: Append node2's remaining children (keys absent from node1) in node2's order. for child2_idx in children2[node2_idx]: child2_key = tree2[child2_idx][0] if child2_key not in tree1_child_keys: copy_subtree(tree2, children2, child2_idx, current_out_idx)Trace Example 1 step by step
Let's trace
tree1 = [[10, -1], [20, 0], [30, 0], [25, 1]]andtree2 = [[10, -1], [30, 0], [40, 0], [35, 1], [45, 2]]:Call Action Row appended Out idx ----------------------------------- ----------------------------------- ------------- ------- merge_nodes(0, 0, parent=-1) combine roots (key 10) [10, -1] 0 copy_subtree(tree1, node=1, p=0) key 20 is only in tree1 -> copy [20, 0] 1 copy_subtree(tree1, node=3, p=1) copy 20's child (key 25) [25, 1] 2 merge_nodes(2, 1, parent=0) key 30 is in both -> combine [30, 0] 3 copy_subtree(tree2, node=3, p=3) key 35 is only in tree2 -> copy [35, 3] 4 copy_subtree(tree2, node=2, p=0) key 40 is unmatched in tree2 -> copy [40, 0] 5 copy_subtree(tree2, node=4, p=5) copy 40's child (key 45) [45, 5] 6The final
merged_rowsis[[10, -1], [20, 0], [25, 1], [30, 0], [35, 3], [40, 0], [45, 5]], matching Example 1.Full solution
from typing import Any, Dict, List, Optional, Set, Tuple def build_children(tree: list[list[int]]) -> list[list[int]]: """Return adjacency lists where children[i] holds node i's child row indices in order.""" node_count = len(tree) # children[i]: list of child row indices of node i, e.g. [[1, 2], [3], [], []] children: list[list[int]] = [[] for _ in range(node_count)] # Scanning rows 1..node_count-1 in order keeps each parent's children ordered by row index. for row_idx in range(1, node_count): parent_idx = tree[row_idx][1] children[parent_idx].append(row_idx) return children def merge_trees_by_key(tree1: list[list[int]], tree2: list[list[int]]) -> list[list[int]]: # Phase 1: Non-empty trees with different root keys cannot be merged at all. if tree1 and tree2 and tree1[0][0] != tree2[0][0]: return [] # Phase 2: Convert upward parent pointers into downward child lists for top-down traversal. children1 = build_children(tree1) children2 = build_children(tree2) # merged_rows: output rows [key, parent_out_idx] appended in preorder. merged_rows: list[list[int]] = [] def copy_subtree( tree: list[list[int]], children: list[list[int]], node_idx: int, parent_out_idx: int, ) -> None: # Record this node's output position right before appending it, so children can point to it. current_out_idx = len(merged_rows) node_key = tree[node_idx][0] merged_rows.append([node_key, parent_out_idx]) for child_idx in children[node_idx]: copy_subtree(tree, children, child_idx, current_out_idx) def merge_nodes(node1_idx: int, node2_idx: int, parent_out_idx: int) -> None: current_out_idx = len(merged_rows) shared_key = tree1[node1_idx][0] merged_rows.append([shared_key, parent_out_idx]) # tree2_child_by_key: {child_key: child_row_idx} for node2's children. # Sibling keys within one tree are distinct, so each key maps to at most one child. tree2_child_by_key: dict[int, int] = {} for child2_idx in children2[node2_idx]: child2_key = tree2[child2_idx][0] tree2_child_by_key[child2_key] = child2_idx # Rule 1: Visit node1's children in node1's order; merge matches, copy non-matches. tree1_child_keys: set[int] = set() for child1_idx in children1[node1_idx]: child1_key = tree1[child1_idx][0] tree1_child_keys.add(child1_key) if child1_key in tree2_child_by_key: merge_nodes(child1_idx, tree2_child_by_key[child1_key], current_out_idx) else: copy_subtree(tree1, children1, child1_idx, current_out_idx) # Rule 2: Append node2's remaining children (keys absent from node1) in node2's order. for child2_idx in children2[node2_idx]: child2_key = tree2[child2_idx][0] if child2_key not in tree1_child_keys: copy_subtree(tree2, children2, child2_idx, current_out_idx) # Phase 3: Merge from both roots, or re-encode whichever single tree is non-empty. if tree1 and tree2: merge_nodes(0, 0, -1) elif tree1: copy_subtree(tree1, children1, 0, -1) elif tree2: copy_subtree(tree2, children2, 0, -1) return merged_rows✅ Submit now — all tests should pass.
Intuition & how it works
Imagine merging two folder trees on your computer (for example, dragging a backup Projects/ folder onto an existing Projects/ folder). Two folders merge into one only when they have the exact same name inside the same parent folder: a "docs" folder inside "backend" never merges with a "docs" folder inside "marketing". Inside any merged folder, you keep the first folder's subfolders in their original order (recursively merging any shared subfolder names), and then append any brand-new subfolders from the second folder at the end. Here, each folder tree is an n-ary tree (a rooted tree where a node can have zero, one, or many children), and we write out the final merged tree in preorder (a top-down listing that records a node first, then completely lists its first child's subtree, then its second child's subtree, and so on).
Why do simpler shortcuts fail? First, you cannot build one global dictionary mapping key -> node across an entire tree, because the same key is allowed to appear at different depths or under different parents, and only siblings under already-merged parents should combine. Second, you cannot slice or reuse raw [key, parent] rows from the input, because the input rows only guarantee parent < row_index (such as breadth-first order), so moving subtrees into preorder changes row positions and requires fresh parent indices. Third, linearly searching tree2's child list for every child of tree1 takes deg(u) * deg(v) steps, which blows up to 10^8 comparisons when two roots each have 10,000 children.
Let's trace a tiny example with tree1 = [[10, -1], [20, 0], [30, 0]] and tree2 = [[10, -1], [30, 0], [40, 0], [35, 1]]:
1. Build child lists:
tree1: root 10 -> [key 20, key 30]
tree2: root 10 -> [key 30 (has child 35), key 40]
2. Combine roots (both have key 10):
append [10, -1] at output index 0
index tree2's root children by key: {30: row 1, 40: row 2}
3. Visit tree1's root children in order:
- key 20: not in {30, 40} -> copy subtree -> append [20, 0] at index 1
- key 30: in {30, 40} -> merge! -> append [30, 0] at index 2,
then copy 30's child 35 -> append [35, 2] at index 3
4. Visit tree2's unmatched root children:
- key 40: not in {20, 30} -> copy subtree -> append [40, 0] at index 4
Output: [[10, -1], [20, 0], [30, 0], [35, 2], [40, 0]]
Complexity
Let n1 = len(tree1) and n2 = len(tree2).
- Time:
O(n1 + n2)on average. Buildingchildren1andchildren2scans each input list once inO(n1 + n2). During the traversal, every input node is visited exactly once — either insidemerge_nodesor insidecopy_subtree. At each combined pair(u, v), buildingtree2_child_by_keyandtree1_child_keysdoesO(deg(u) + deg(v))dictionary and set operations (O(1)average time each), and summing degrees over all nodes in both trees is at mostn1 + n2. - Space:
O(n1 + n2). Storingchildren1,children2, andmerged_rowstakesO(n1 + n2)space. The call stack (the chain of active function calls waiting to finish) is at most500frames deep by the path-length constraint, and the per-node dictionaries/sets alive along a single root-to-leaf path have total size at mostn1 + n2.
Edge cases
- Different root keys: when both trees are non-empty and
tree1[0][0] != tree2[0][0], return[]immediately, even if lower subtrees share keys. - Exactly one empty tree: return the non-empty tree re-encoded in preorder via
copy_subtree, because its input rows might be in breadth-first or interleaved order rather than preorder. - Both trees empty: return
[]. - Single-node trees:
[[5, -1]]and[[5, -1]]combine into[[5, -1]];[[5, -1]]and[[6, -1]]return[]. - Same key under different parents or depths: key
9under parent4intree1and key9under parent7intree2are not combined; both copies remain under their respective parents. - Copied subtrees keep original order: an unmatched subtree from
tree2preservestree2's child order, never sorted order by key. - Wide stars (
10^4children) and deep chains (500nodes): dictionary matching keeps wide nodes linear, and depth500stays safely below Python's recursion limit.
Common mistakes
- Returning a single non-empty input tree verbatim (
if not tree1: return tree2): input rows are only topologically ordered (parent < i), not necessarily in preorder, so parent indices and row order can be wrong without runningcopy_subtree. - Matching keys with one global dictionary per tree: keys are only unique among siblings of the same parent, not across the whole tree; matching globally merges unrelated nodes from different branches.
- Reusing input parent indices in
merged_rows: a node's parent index in the output must becurrent_out_idx(its parent's index inmerged_rows), nottree[node_idx][1]. - Sorting children by key: the problem requires
tree1's child order first, followed bytree2's unmatched children intree2's order. - Linearly scanning
children2[node2]for each child ofnode1: turns wide trees intoO(n1 * n2)instead ofO(n1 + n2).
Alternative approaches
- Build explicit merged tree nodes, then serialize: construct an in-memory tree of
Node(key, children)objects during the merge and run a second preorder pass to produce[key, parent]rows. It has the sameO(n1 + n2)complexity, but emitting rows directly intomerged_rowsduring recursion avoids allocating intermediate node objects. - Iterative traversal with an explicit stack: eliminates recursion limits when trees can be arbitrarily deep (see the first follow-up below).
Follow-up questions
- How would you avoid hitting Python's recursion limit if root-to-leaf paths could reach 10^5 nodes? Deep chains would hit Python's
RecursionErrorlimit (1,000stack frames by default). Replace recursion with an explicit stack of(node1_idx, node2_idx, parent_out_idx)tuples (usingNonewhen a subtree exists in only one tree): popping a tuple appends its[key, parent_out_idx]row atcurrent_out_idx = len(merged_rows)and pushes its child tasks in reverse order so the first child is popped next, preserving exact preorder inO(n1 + n2)time and space. - How would the algorithm change if a single parent could have duplicate child keys? "The child with the same key" would become ambiguous, so you would first clarify the pairing rule with the interviewer — typically pairing the 1st occurrence of key
kundernode1with the 1st occurrence ofkundernode2, the 2nd with the 2nd, and so on. You can implement this inO(n1 + n2)time by mapping each key innode2to a queue (collections.deque) of child indices and popping from the front each timenode1has a matching key, then copying any leftover unmatched occurrences fromnode2. - How would you generalize this function to merge a list of k trees? First verify that all non-empty trees share the same root key (otherwise return
[]right away so an intermediate[]from a mismatch is not mistaken for an empty input tree!). Folding pairwise (merge(merge(T_1, T_2), T_3)...) works cleanly because inputs and outputs share the exact same encoding, though re-scanning the accumulated tree costs up toO(k * N)forNtotal nodes; to achieve optimalO(N)time, traverse all active matched nodes across thektrees simultaneously, grouping their children by first-seen key order in a dictionary.
Follow-up questions
- How would you avoid hitting Python's recursion limit if root-to-leaf paths could reach 10^5 nodes?
- How would the algorithm change if a single parent could have duplicate child keys?
- How would you generalize this function to merge a list of k trees?
Similar questions
- Indexed Word Distance Queries
- Largest Value from Concatenated Integers
- Non-Adjacent Flowerbed Placement
- Validate Plain Signed Decimal Strings
- Stack vs. Heap Memory
- Find Downstream Impacted Microservices
More LinkedIn interview questions
- Shortest-Path Robot Navigation on an Unmapped Grid Medium
- Longest Root-to-Leaf Depth from Child Pairs Medium
- Runner-Up Score in a Knockout Min-Tree Medium Pro
- Repeated Word Proximity Queries Hard Pro
- Zigzag Depth-Order Tree Traversal Medium Pro
- Non-Adjacent Flowerbed Placement Medium Pro
- Queue Pooling, Skewed Graphs, and Shrinkage Medium Pro
- Distributed Key-Value Store for Small-Team Internal Services Medium Pro
- Two-Project Architecture and Trade-Off Walkthrough Medium Pro
- Defending a Hard Architectural Trade-Off and Its Implementation Medium Pro