Given two binary trees, merge them together using the following guidelines:
- For overlapping nodes, sum the weight together as the weight of the new node.
- For non-overlapping nodes, add the not NULL node to the new tree.
The image below shows a sample merge with two binary trees.
Sample Input:
tree1 = [2, 3, 1, 6, 4], tree2 = [7, 5, 9, null, null, 10, 12]
Sample Output:
[9, 8, 10, 6, 4, 10, 12]
数据结构和算法:初级练习题 #34 – 合并二叉树
给定两颗二叉树,把它们按照下面的规则合并在一起:
- 相同位置的节点,把两个节点的重量相加。
- 没有重合的节点,把非空节点加入到新的二叉树中。
上面的图例展示了两颗二叉树合并的结果。
输入样例:
tree1 = [2, 3, 1, 6, 4], tree2 = [7, 5, 9, null, null, 10, 12]
输出样例:
<9, <8, <6, None, None>, <4, None, None>>, <10, <10, None, None>, <12, None, None>>>