← Questions

Merge two n-ary trees by child position

0
MicrosoftCoding

A coding interview question asked at Microsoft. It tests trees, recursion and dfs.

Implement merge_trees(root1, root2). It takes the roots of two n-ary trees and returns the root of a new tree that merges them.

Each node has an integer val and an ordered list children:

class TreeNode:
    val: int
    children: list[TreeNode]

Nodes are matched by position: the roots match, and the child at index i of a matched pair matches the child at index i of the other node.

  • If both trees have a node at a position, the merged node's value is the sum of the two values.
  • If only one tree has a node at a position, the merged tree contains a copy of that whole subtree.
  • The result must not share any node objects with the inputs. Do not modify the inputs.

Either root may be None. If both are None, return None.

Constraints

  • Each tree has 0 to 10^5 nodes, and a tree can be up to 10^5 levels deep.
  • Node values are in [-10^4, 10^4].

Example 1

Tree A:        Tree B:
    1              2
   / \           / | \
  3   2         1  3  7
  |            / \    |
  5           4   6   8

Merged:
      3
   /  |  \
  4   5   7
 / \      |
9   6     8

The roots give 1 + 2 = 3. Child 0 gives 3 + 1 = 4, and its children give 5 + 4 = 9 and a copy of 6. Child 1 gives 2 + 3 = 5. Child 2 exists only in B, so its subtree 7 -> 8 is copied.

Example 2

merge_trees(None, TreeNode(4, [TreeNode(-1)])) returns a new tree 4 -> -1. Changing the result does not change the input tree.

Clarifying questions

  • Should the result be built even when one root is None, as a full copy of the other tree?
  • Is changing the inputs ever allowed? (No.)
  • Can the trees be deep enough to break recursion? (Yes, 10^5 levels.)
  • Are children matched only by position, never by value?

What a strong answer covers

  • Uses an explicit stack of (node_a, node_b, new_node) triples, so deep trees do not overflow the call stack.
  • For each pair, creates the new node with the summed value, then pushes a triple for each child index up to the longer child list. A missing side is None.
  • Copies a subtree that exists on only one side through the same loop, with the other side None, so no node is shared.
  • That is O(n_a + n_b) time and memory.
  • Tests both None, one None, different child counts, a deep chain, and that changing the result does not change the inputs.

Follow-ups

  • Match children by value or key instead of position.
  • Merge in place into the first tree, reusing its nodes.
  • Merge k trees at once.
  • Binary trees with the same rules.

Where it's asked

What it tests

trees · recursion · dfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding