← 返回 meta 的题目列表Merge Two Trees with Unique Keys
类型:online_judge
Given two trees where each node consists of a key-value pair {key: value} and each node can have multiple child nodes. The keys are unique under the same parent node. You are required to merge the two trees by summing up the values of nodes with the same key and including unmatched keys as child nodes in the resulting tree.
Input Format
Two trees, represented as tree1 = {'A': (3, [{'F': 3}, {'B': 1}, {'R': 6}])} and tree2 = {'A': (8, [{'F': 7}, {'R': 3}])}. Trees are expressed in this nested dictionary and list format.
Output Format
The merged tree, e.g., {'A': (11, [{'F': 10}, {'B': 1}, {'R': 9}])}.
Constraints
Each node's key and value are integers.
Assume keys are unique.
Test Cases
assert merge_trees({'A': (3, [{'F': 3}, {'B': 1}, {'R': 6}])}, {'A': (8, [{'F': 7}, {'R': 3}])}) == {'A': (11, [{'F': 10}, {'B': 1}, {'R': 9}])}
``
Example
Input
{'A': (3, [{'F': 3}, {'B': 1}, {'R': 6}])}, {'A': (8, [{'F': 7}, {'R': 3}])}