Merge Two Binary Trees

Easy Trees & BST Recursion

Merge Two Binary Trees is a easy trees & bst problem solved with the recursion pattern. The best approach, optimal (recursion, reuse the nodes), runs in O(min(n1, n2)) time and O(min(h1, h2)) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (build a brand-new tree) up.

Problem

You are given the roots of two binary trees, root1 and root2. Picture placing one tree exactly on top of the other, with the two roots on the same spot. At some positions both trees have a node, and at others only one of them does (or neither).

Build the merged tree by these rules, position by position, starting at the roots:

  • If both trees have a node at a position, the merged tree has a node there whose value is the sum of the two values.
  • If only one tree has a node at a position, the merged tree uses that node (with everything below it) as it is.
  • If neither tree has a node there, the merged tree has none either.

Return the root of the merged tree. If both trees are empty, return an empty tree.

Examples

Example 1

Input
root1 = [5, 2, 4, 1], root2 = [3, 1, 6, null, 7, null, 2]
Output
[8, 3, 10, 1, 7, null, 2]
Why
Lay the second tree over the first. The roots overlap and add up to 5 + 3 = 8, the left children to 2 + 1 = 3 and the right children to 4 + 6 = 10. The 1 under the left child exists only in the first tree, and the 7 and the 2 exist only in the second, so they are copied over unchanged.

Example 2

Input
root1 = [1, 2], root2 = [1, null, 2]
Output
[2, 2, 2]
Why
Only the roots overlap: 1 + 1 = 2. The first tree brings a left child 2 and the second tree brings a right child 2.

Example 3

Input
root1 = [], root2 = [4, -1]
Output
[4, -1]
Why
The first tree is empty, so the result is simply the second tree.

Constraints

  • Each tree has between 0 and 2000 nodes.
  • -10^4 <= Node.val <= 10^4

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 35 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (build a brand-new tree)O(n1 + n2)O(n1 + n2)
Iterative (stack of node pairs)O(min(n1, n2))O(min(n1, n2))
Optimal (recursion, reuse the nodes)O(min(n1, n2))O(min(h1, h2))

1Brute force (build a brand-new tree)

TimeO(n1 + n2)Every node of both trees is visited once, including the parts that exist in only one tree, since they are copied.
SpaceO(n1 + n2)The result is a fresh tree with up to n1 + n2 nodes, and the recursion goes as deep as the taller tree.

Leave both inputs untouched and build the result from scratch. A position exists in the merged tree when at least one of the trees has a node there. Its value is the sum of the values present, counting a missing node as 0. Create that node, then fill its left side from the two left children and its right side from the two right children. When one tree runs out, the recursion keeps going down the other one alone and copies it node by node.

  1. If both nodes are null, return null.
  2. Let val be the sum of the values that exist (a null node adds 0) and create a new node with it.
  3. Its left child is the merge of the two left children (use null for the side that is missing).
  4. Its right child is the merge of the two right children.
  5. Return the new node.
class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) return null;
        int val = (root1 == null ? 0 : root1.val) + (root2 == null ? 0 : root2.val);
        TreeNode node = new TreeNode(val);
        node.left = mergeTrees(root1 == null ? null : root1.left, root2 == null ? null : root2.left);
        node.right = mergeTrees(root1 == null ? null : root1.right, root2 == null ? null : root2.right);
        return node;
    }
}

2Iterative (stack of node pairs)

TimeO(min(n1, n2))A pair is pushed only for a position where the first tree has a node and the second tree's parent had one too, so the work is bounded by the overlapping positions (plus one null check per pushed pair). Subtrees present in one tree only are attached in O(1).
SpaceO(min(n1, n2))The stack can hold pairs from many pending branches at once, at most one per overlapping position.

Merge into the first tree, without recursion. A stack holds pairs of nodes at the same position, one from each tree, where the first-tree node is known to exist. Pop a pair. If the second node is missing there is nothing to add. Otherwise add its value into the first node. Then look at each side: if the first tree has a gap there, hang the second tree's child in the gap, whole subtree at once; if it has a child, push that pair to merge it later.

  1. If root1 is null, return root2.
  2. Push the pair (root1, root2).
  3. Pop a pair (a, b). If b is null, continue.
  4. Add b.val to a.val.
  5. If a.left is null, set a.left = b.left; otherwise push (a.left, b.left). Do the same on the right.
  6. When the stack is empty, return root1.
class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        Deque<TreeNode[]> stack = new ArrayDeque<>();
        stack.push(new TreeNode[] { root1, root2 });
        while (!stack.isEmpty()) {
            TreeNode[] pair = stack.pop();
            TreeNode a = pair[0], b = pair[1];
            if (b == null) continue;
            a.val += b.val;
            if (a.left == null) a.left = b.left;
            else stack.push(new TreeNode[] { a.left, b.left });
            if (a.right == null) a.right = b.right;
            else stack.push(new TreeNode[] { a.right, b.right });
        }
        return root1;
    }
}

3Optimal (recursion, reuse the nodes)

TimeO(min(n1, n2))The recursion goes on only while both trees have a node, so it visits each overlapping position once. A subtree that exists in one tree only is returned in O(1).
SpaceO(min(h1, h2))The call stack is as deep as the deepest overlapping position, at most the height of the shorter tree. No new nodes are created.

Merge the second tree into the first one. If the first node is missing, the answer at this position is simply the second node with everything below it, and the same holds the other way round. Only when both nodes exist is there work to do: add the second value into the first node, merge the two left subtrees and the two right subtrees, store the results as the first node's children, and return the first node. Whole subtrees that exist in only one tree are reused without being visited.

  1. If root1 is null, return root2.
  2. If root2 is null, return root1.
  3. Add root2.val to root1.val.
  4. root1.left = mergeTrees(root1.left, root2.left).
  5. root1.right = mergeTrees(root1.right, root2.right).
  6. Return root1.
class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        if (root2 == null) return root1;
        root1.val += root2.val;
        root1.left = mergeTrees(root1.left, root2.left);
        root1.right = mergeTrees(root1.right, root2.right);
        return root1;
    }
}

Edge cases to test

  • Both trees are empty: the answer is an empty tree
  • One tree is empty: the answer is the other tree, unchanged
  • The trees have exactly the same shape: every node is a sum
  • The trees do not overlap below the root (one only goes left, the other only right)
  • Values that cancel out: 5 and -5 merge into a node with value 0, which must stay in the tree
  • Long chains of up to 2000 nodes: a recursive solution goes 2000 calls deep

Hints

Hint 1

Look at one position at a time. If both trees have a node there, the merged node holds the sum. If only one tree has a node there, its whole subtree can be used as it is.

Hint 2

The rule for a position is the same as the rule for the whole tree, so recursion fits: merge the left children, merge the right children.

Hint 3

You do not need new nodes. Add the second tree's value into the first tree's node and hang the second tree's subtree wherever the first tree has a gap.

FAQ

What is the best time complexity for Merge Two Binary Trees?

Optimal (recursion, reuse the nodes) runs in O(min(n1, n2)) time and O(min(h1, h2)) extra space. The recursion goes on only while both trees have a node, so it visits each overlapping position once. A subtree that exists in one tree only is returned in O(1).

Which pattern does Merge Two Binary Trees use?

It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).

Is there a brute force solution for Merge Two Binary Trees?

Yes. Brute force (build a brand-new tree) takes O(n1 + n2) time and O(n1 + n2) space. Leave both inputs untouched and build the result from scratch.

Which edge cases should I test for Merge Two Binary Trees?

Both trees are empty: the answer is an empty tree; One tree is empty: the answer is the other tree, unchanged; The trees have exactly the same shape: every node is a sum; The trees do not overlap below the root (one only goes left, the other only right); Values that cancel out: 5 and -5 merge into a node with value 0, which must stay in the tree; Long chains of up to 2000 nodes: a recursive solution goes 2000 calls deep.