merge-two-binary-trees.sh — zsh

Merge Two Binary Trees

easy
binary-treedepth-first-searchrecursion

You are given the roots of two binary trees t1 and t2.

Imagine that when you overlay one tree on top of the other, some nodes of the two trees line up while others do not. Merge the two trees into a new binary tree: if two nodes overlap, the new node's value is the sum of both nodes' values; otherwise the non-null node becomes the new tree's node.

Return the merged tree's root.

Input / output

  • Input: t1: TreeNode, t2: TreeNode (JSON test fixtures are LeetCode-style level-order arrays, e.g. [1,3,2,5], with null for a missing child)
  • Output: TreeNode (also a level-order array)

Constraints

  • 0 <= number of nodes in each tree <= 2,000
  • -10,000 <= node value <= 10,000

Follow-up

Can you merge the trees in place, mutating t1 to become the merged result instead of allocating new nodes?

Examples
Example 1
Input: t1 = [1,3,2,5], t2 = [2,1,3,null,4,null,7]
Output: [3,4,5,5,4,null,7]
Example 2
Input: t1 = [1], t2 = [1,2]
Output: [2,2]
Example 3 (both empty)
Input: t1 = [], t2 = []
Output: []
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.