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, entry i is [key, parent]: entry 0 is the root with parent = -1, and every entry i >= 1 has 0 <= parent < i referencing 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 tree1 and tree2 are 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 [].
  • Aligned fusion: Node u from tree1 and node v from tree2 fuse into one output node if and only if u and v share 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 (from tree1) and v (from tree2) fuse, their merged node retains their common key and orders its direct children as follows:
    1. First, each child of u in u's original child order — recursively fused with v's child of the same key if present, or copied intact with its subtree otherwise.
    2. Next, each child of v whose key does not occur among u's children, in v's original child order, copied intact with its subtree.
  • 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], where parent_idx is -1 for 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^4 and 0 <= len(tree2) <= 10^4
  • -10^9 <= key <= 10^9
  • In any non-empty input, entry 0 has parent == -1, and every entry i >= 1 satisfies 0 <= 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 500 nodes.

Step-by-step walkthrough

  1. 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 0 is always the root, with parent_row = -1.
    • Every later row i points to an earlier row 0 <= parent_row < i as 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 tree1 from 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 tree2 were empty, we could not return tree1 unchanged: in preorder, key 25 moves to row 2 and key 30 moves to row 3! That means we always build fresh output rows with newly assigned parent indices.

  2. 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 node i.

    Because we scan row_idx from 1 up to len(tree) - 1 in increasing order, appending row_idx to children[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 children
    

    This single pass takes O(n) time and O(n) space for an n-node tree.

  3. 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 9 under parent 4 never combines with a key 9 directly under root 7.

    Here is how Example 1 combines tree1 and tree2:

         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 (in tree1) and node2 (in tree2) are combined:

    1. Walk node1's children in tree1's order. If node2 has a child with the same key, recursively combine those two children; otherwise copy node1's child and its whole subtree.
    2. Walk node2's children in tree2's order. For any child whose key did not appear among node1's children, copy that child and its whole subtree.

    How do we check whether node2 has a child with child1_key? Scanning children2[node2] linearly for every child of node1 would take deg(node1) * deg(node2) steps — up to 10^4 * 10^4 = 10^8 comparisons when two roots each have 10,000 children! Because sibling keys under any single parent are guaranteed distinct, we first put node2's children into a dictionary tree2_child_by_key = {key: child2_idx} so each lookup takes O(1) average time.

  4. 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 is current_out_idx = len(merged_rows) right before appending. Passing current_out_idx down to each recursive child call gives every child its exact parent_out_idx.

    For an unmatched node whose entire subtree comes from just one tree, copy_subtree writes 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 500 nodes, recursion uses at most 500 stack frames, safely within Python's default limit of 1,000.

  5. Combine two matched nodes in the required child order

    merge_nodes(node1_idx, node2_idx, parent_out_idx) emits the combined node, indexes node2's children by key, processes node1's children first (recording their keys in tree1_child_keys), and finally appends node2's unmatched children.

    At the top level of merge_trees_by_key: - If both trees are non-empty and tree1[0][0] != tree2[0][0], return [] immediately. - If both are non-empty (so root keys match), call merge_nodes(0, 0, -1). - If only one tree is non-empty, call copy_subtree(..., 0, -1) to re-encode it in preorder. - If both are empty, merged_rows remains [].

    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)
    
  6. Trace Example 1 step by step

    Let's trace tree1 = [[10, -1], [20, 0], [30, 0], [25, 1]] and tree2 = [[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]        6
    

    The final merged_rows is [[10, -1], [20, 0], [25, 1], [30, 0], [35, 3], [40, 0], [45, 5]], matching Example 1.

  7. 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. Building children1 and children2 scans each input list once in O(n1 + n2). During the traversal, every input node is visited exactly once — either inside merge_nodes or inside copy_subtree. At each combined pair (u, v), building tree2_child_by_key and tree1_child_keys does O(deg(u) + deg(v)) dictionary and set operations (O(1) average time each), and summing degrees over all nodes in both trees is at most n1 + n2.
  • Space: O(n1 + n2). Storing children1, children2, and merged_rows takes O(n1 + n2) space. The call stack (the chain of active function calls waiting to finish) is at most 500 frames deep by the path-length constraint, and the per-node dictionaries/sets alive along a single root-to-leaf path have total size at most n1 + 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 9 under parent 4 in tree1 and key 9 under parent 7 in tree2 are not combined; both copies remain under their respective parents.
  • Copied subtrees keep original order: an unmatched subtree from tree2 preserves tree2's child order, never sorted order by key.
  • Wide stars (10^4 children) and deep chains (500 nodes): dictionary matching keeps wide nodes linear, and depth 500 stays 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 running copy_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 be current_out_idx (its parent's index in merged_rows), not tree[node_idx][1].
  • Sorting children by key: the problem requires tree1's child order first, followed by tree2's unmatched children in tree2's order.
  • Linearly scanning children2[node2] for each child of node1: turns wide trees into O(n1 * n2) instead of O(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 same O(n1 + n2) complexity, but emitting rows directly into merged_rows during 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 RecursionError limit (1,000 stack frames by default). Replace recursion with an explicit stack of (node1_idx, node2_idx, parent_out_idx) tuples (using None when a subtree exists in only one tree): popping a tuple appends its [key, parent_out_idx] row at current_out_idx = len(merged_rows) and pushes its child tasks in reverse order so the first child is popped next, preserving exact preorder in O(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 k under node1 with the 1st occurrence of k under node2, the 2nd with the 2nd, and so on. You can implement this in O(n1 + n2) time by mapping each key in node2 to a queue (collections.deque) of child indices and popping from the front each time node1 has a matching key, then copying any leftover unmatched occurrences from node2.
  • 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 to O(k * N) for N total nodes; to achieve optimal O(N) time, traverse all active matched nodes across the k trees simultaneously, grouping their children by first-seen key order in a dictionary.

Follow-up questions

Similar questions

More LinkedIn interview questions

All 154 LinkedIn questions →