Skip to Content

Merge Two Binary Trees

Home | Coding Interviews | Simple Data Structures | Merge Two Binary Trees

You are given two binary trees root1 and root2.

Imagine the trees are layed ontop of each other. The merged nodes will have the sum of the values of the original nodes. If one or the other is null, treat the null node as if it had a value of 0.

Return the merged tree.

class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null) return t2;
        if (t2 == null) return t1;

        TreeNode node = new TreeNode(t1.val + t2.val);
        node.left = mergeTrees(t1.left, t2.left);
        node.right = mergeTrees(t1.right, t2.right);
        return node;
    }
}

Posted by Jamie Meyer 25 days ago