You are given two N-ary trees A and B. Each node has:
-
key
(string): unique among siblings (i.e., within a node’s children list, no two children share the same key)
-
value
(any scalar, e.g., string/int)
-
children
(list of nodes)
You must produce a merged tree M = merge(A, B) using these rules:
Merge rules
-
If a node exists in both trees at the same position (matched by
key)
:
-
The merged node’s
key
stays the same.
-
The merged node’s
value
is
taken from tree B
(i.e.,
B
overwrites
A
).
-
The merged node’s
children
are formed by merging children lists by key, recursively.
-
If a child key exists only in one tree
:
-
Include that subtree unchanged in the output.
Assume the two input roots have the same key.
Task
Implement a function to merge the two trees and return the merged root.
Constraints
-
Total nodes across both trees: up to
2 * 10^5
-
Keys are non-empty strings
Clarifications
-
Sibling order in the output does not matter unless you choose to preserve a stable order.