LeetCode 617: Merge Two Binary Trees Solution

Master LeetCode problem 617 (Merge Two Binary Trees), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To merge two binary trees, we need to traverse both trees simultaneously. At each step, we check if the current nodes in both trees are not null. If both nodes are not null, we update the value of the node in the first tree by adding the value of the corresponding node in the second tree. If one of the nodes is null, we take the non-null node as the merged node. If both nodes are null, the merged node will also be null. We then recursively merge the left subtree and right subtree of both trees.

Time Complexity: O(n) where n is the total number of nodes in the smaller tree Space Complexity: O(n) for the recursive call stack

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 617 (Merge Two Binary Trees)?

This page provides optimized solutions for LeetCode problem 617 (Merge Two Binary Trees) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 617 (Merge Two Binary Trees)?

The time complexity for LeetCode 617 (Merge Two Binary Trees) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 617 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 617 in Java, C++, or Python.

Back to LeetCode Solutions