FunctionRacerProblemsRace

Merge Two Binary Trees

EasyTreesPython, JavaScript, TypeScript, Java, C++

Lay the tree root2 on top of root1. Where both trees have a node in the same position, the merged node holds the sum of the two values. Where only one tree has a node, the merged tree simply uses that node (with its whole subtree). Return the root of the merged tree.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root1 [1,3,2,5]
root2 [2,1,3,null,4,null,7]
returns [3,4,5,5,4,null,7]

Root: 1+2 = 3. Left: 3+1 = 4. Right: 2+3 = 5. The merged tree is [3,4,5,5,4,None,7].

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems