Skip to problem
←

Merge Two Binary Trees

Easy 0 attempts

You get the roots of two binary trees. Build a merged tree as follows. Start from both roots. If both nodes exist at the same position, the merged node’s value is the sum of the two values. If only one side exists, that node is used as in that tree. Return the root of the merged tree.

You may reuse nodes from the inputs instead of building a completely separate tree, if you prefer.

Match nodes by their position from the root (the same sequence of left/right steps), not by value or traversal order. A subtree present in only one input is kept in full. If both trees are empty, return null.

For t1 = [1,2] and t2 = [3,null,4], the roots sum to 4; the left 2 and right 4 are retained, giving [4,2,4].

Function contract

Implement mergeTrees(t1, t2). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the merged root node, or null when both trees are empty. The runner displays the tree in level order and trims trailing nulls.

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 = []
t2 = [1]
Output
[1]
Constraints
  • Each tree contains between 0 and 2000 nodes
  • -10^4 <= Node.val <= 10^4

Recursive DFS

Recurse on matching node positions. If either node is missing, return the other subtree unchanged. Otherwise create a node containing the sum and merge the corresponding left and right children. This implementation shares one-sided subtrees with the inputs, which the contract permits.

javascript
function mergeTrees(t1, t2) {
  if (!t1) return t2;
  if (!t2) return t1;
  return {
    val: t1.val + t2.val,
    left: mergeTrees(t1.left, t2.left),
    right: mergeTrees(t1.right, t2.right)
  };
}

Time: O(min(n1, n2) + 1), since recursion continues only through positions present in both trees; one-sided subtrees are reused without traversal.

Space: O(h) recursion stack, plus O(min(n1, n2)) new output nodes in the worst case, where h is the depth of the overlapping portion.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript