Combine Tree Structures with Ordered Name Matching
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests recursive tree traversal with order-sensitive child pairing by name occurrence and careful handling of unmatched nodes.
You are given two tree structures where each node is represented as a dictionary containing three keys:
name: a string identifiervalue: an integerchildren: a list of child nodes (ordered)
Your task is to combine these trees into a new tree following specific merging rules.
Merging Rules
When combining a node from the first tree with a node from the second tree:
-
Name and Value: The resulting node takes its name from the first tree and its value from the second tree.
-
Child Pairing: Children are matched by name based on their order of occurrence. For each distinct name, the first child with that name in tree one pairs with the first child with that name in tree two, the second pairs with the second, and so on. Each matched pair is recursively combined using these same rules.
-
Result Structure: The merged node's children list is constructed as follows:
- First, include all children from the first tree in their original order. If a child was paired, replace it with the recursively merged result. If unpaired, include it unchanged along with its entire subtree.
- Then, append all unpaired children from the second tree in their original order, each with its complete subtree.
-
Root Handling: The root nodes are always merged together, regardless of whether their names match.
Output Format
Return a new tree where every node has exactly the keys name, value, and children. Leaf nodes have children set to an empty list []. The order of elements in every children list matters.
Constraints
- Each tree contains between 1 and 10⁴ nodes
- Maximum tree depth is 500 nodes on the longest root-to-leaf path
- Node names are non-empty strings of at most 20 lowercase letters and digits
- Siblings may have duplicate names; names can appear anywhere in either tree
- Node values are integers where -10⁹ ≤ value ≤ 10⁹
- The resulting merged tree has fewer than 2 × 10⁴ nodes
Examples
Example 1
Input: combine_trees({'name': 'root', 'value': 1, 'children': [{'name': 'a', 'value': 2, 'children': []}, {'name': 'b', 'value': 3, 'children': []}]}, {'name': 'top', 'value': 10, 'children': [{'name': 'b', 'value': 30, 'children': []}, {'name': 'c', 'value': 40, 'children': []}]})
Output: {'name': 'root', 'value': 10, 'children': [{'name': 'a', 'value': 2, 'children': []}, {'name': 'b', 'value': 30, 'children': []}, {'name': 'c', 'value': 40, 'children': []}]}
Example 2
Input: combine_trees({'name': 'r', 'value': 0, 'children': [{'name': 'x', 'value': 1, 'children': [{'name': 'y', 'value': 2, 'children': []}]}, {'name': 'z', 'value': 3, 'children': []}, {'name': 'x', 'value': 4, 'children': []}]}, {'name': 'r', 'value': 9, 'children': [{'name': 'x', 'value': 5, 'children': [{'name': 'w', 'value': 6, 'children': []}, {'name': 'y', 'value': 7, 'children': []}]}, {'name': 'x', 'value': 8, 'children': []}, {'name': 'x', 'value': 11, 'children': [{'name': 'v', 'value': 12, 'children': []}]}]})
Output: {'name': 'r', 'value': 9, 'children': [{'name': 'x', 'value': 5, 'children': [{'name': 'y', 'value': 7, 'children': []}, {'name': 'w', 'value': 6, 'children': []}]}, {'name': 'z', 'value': 3, 'children': []}, {'name': 'x', 'value': 8, 'children': []}, {'name': 'x', 'value': 11, 'children': [{'name': 'v', 'value': 12, 'children': []}]}]}
Hints
Hint 1
Build an index mapping each name to the positions of children with that name in the second tree
Hint 2
Track which occurrence of each name you've already paired by maintaining a pointer for each distinct name
Hint 3
Mark which children from the second tree have been paired so you know which ones to append at the end
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution uses recursion to merge corresponding nodes. The challenge lies in correctly pairing children when siblings can share names.
The key insight is to track occurrences of each name separately. When tree one has multiple children named "x" and tree two also has multiple "x" children, we pair the first "x" from tree one with the first "x" from tree two, the second with the second, and so on.
Algorithm:
-
For each pair of nodes being merged, first index the second tree's children by name. Store each name mapped to a list of child indices having that name, preserving order.
-
Walk through the first tree's children in order. For each child, check if a matching name exists in the second tree that hasn't been paired yet. Use a pointer per name to track which occurrence we've reached.
-
If a match exists, mark it as paired, recursively merge the two children, and add the result to the output. If no match exists, add the first tree's child unchanged.
-
After processing all first-tree children, append any unpaired children from the second tree in their original order.
-
Return a new node with the first tree's name, second tree's value, and the constructed children list.
Why It Works
-
Occurrence-based pairing: By maintaining indices per name and a pointer tracking which occurrence we've used, we correctly implement "j-th occurrence pairs with j-th occurrence" semantics.
-
Order preservation: We iterate through the first tree's children once in order, ensuring they appear in their original positions. Unpaired second-tree children are appended in a separate pass, maintaining their relative order.
-
Completeness: The paired flags ensure every second-tree child is either merged with its partner or appended as unpaired, with no children lost or duplicated.
Complexity
Time: O(n₁ + n₂) where n₁ and n₂ are the node counts. Each node is visited at most once as either the first or second argument to a merge call. Within each call, the work is linear in the number of children, with constant-time hash operations.
Space: O(n₁ + n₂) for the output tree, index structures, and paired-tracking arrays. The recursion stack depth is bounded by the maximum tree depth of 500.
def combine_trees(t1, t2):
def merge(a, b):
bkids = b["children"]
by_name = {}
for idx, c in enumerate(bkids):
by_name.setdefault(c["name"], []).append(idx)
ptr = {}
paired_b = [False] * len(bkids)
out = []
for c in a["children"]:
nm = c["name"]
lst = by_name.get(nm)
p = ptr.get(nm, 0)
if lst is not None and p < len(lst):
ptr[nm] = p + 1
j = lst[p]
paired_b[j] = True
out.append(merge(c, bkids[j]))
else:
out.append(c)
for j, c in enumerate(bkids):
if not paired_b[j]:
out.append(c)
return {"name": a["name"], "value": b["value"], "children": out}
return merge(t1, t2)