The problem. You are given two binary trees a and b. Imagine laying one on top of the other. Where both trees have a node, the merged node's value is the sum of the two. Where only one tree has a node, that node (with everything under it) is used as it is. Return the merged tree.
Input: a = [1, 3, 2, 5], b = [2, 1, 3, null, 4, null, 7]
Output: [3, 4, 5, 5, 4, null, 7]
Input: a = [1], b = [1, 2] Output: [2, 2]The two trees must be walked in step: the same position in both at once — root with root, left child with left child. It's the Same Tree walk, combining instead of comparing.
Free account
Sign up to read the rest of this lesson: 6 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come