Problem 408
Merge Two Binary Trees
Easy · 10 pts · Tree, Depth-First Search, Binary Tree
Problem
Merge two binary trees by placing one on top of the other. Where both trees have a node at the same position, the merged node's value is the sum of the two values. Where only one tree has a node, that node (with its whole subtree) is used as it is. Print the merged tree in level order.
Input
The first tree, then the second tree, each as two lines: the token count N and the N level-order tokens ('null' for missing children).
Output
Print the merged tree in level order with 'null' for missing children and no trailing nulls, separated by spaces.
Constraints
1 <= number of nodes in each tree <= 2000; -10000 <= value <= 10000
Example input
4 1 3 2 5 7 2 1 3 null 4 null 7
Example output
3 4 5 5 4 null 7
Explanation
Overlaying 1 / 3 2 / 5 with 2 / 1 3 / _ 4 _ 7 adds the overlapping roots (1 + 2 = 3) and children (3 + 1 = 4, 2 + 3 = 5) and keeps the nodes 5, 4 and 7 that exist in only one tree.