oneby7

Binary Trees Depth first: return a value up

357. Merge Two Binary Trees

Easy

You are given root1 and root2, the root nodes of two binary trees. Merge the two trees into one and return the root of the merged tree.

Picture one tree laid over the other, root on root. Two nodes are in the same place when the same steps to the left and to the right lead to them from their roots. Where both trees have a node in the same place, the merged tree has one node there, holding the sum of the two values. Where only one tree has a node, the merged tree keeps that node and everything below it. Where neither tree has a node, the merged tree has none.

The examples write a tree level by level, from left to right, with null where a child is missing. So root1 = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out. The output shows the tree you return the same way.

Example 1

root1
-2346
root2
2851
output
283356

Input: root1 = [4, -2, 6, null, 3] root2 = [1, 5, null, 8, null, 2]

Output: [5,3,6,8,3,null,null,2]

Explanation: Both trees have the root and its left child, so those places hold 4 + 1 = 5 and −2 + 5 = 3. The rest is in one tree only: 6 and 3 come from root1, and 8 with its child 2 comes from root2.

Example 2

-94
root2
-94
output

Input: root1 = [], root2 = [-9, null, 4]

Output: [-9,null,4]

Explanation: root1 is empty, so the merged tree is root2 as it is.

Example 3

2-5
root1
-251
root2
001
output

Input: root1 = [-5, 2], root2 = [5, -2, 1]

Output: [0,0,1]

Explanation: The root and its left child both add up to 0. They are still nodes, so they stay in the tree with the value 0. The right child 1 comes from root2 alone.

Check your understanding

Work out the answer for this input before you write any code.

root1 = [1, 2], root2 = [3, null, 4]

Constraints

  • 0 ≤ number of nodes in each tree ≤ 105
  • -5·108 ≤ Node.val ≤ 5·108
  • Each tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.