Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Merge Two Binary Trees

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "617" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given two binary trees root1 and root2. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree. Return the merged tree. Note: The merging process must start from the root nodes of both trees. Example 1: Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] Output: [3,4,5,5,4,null,7] Example 2: Input: root1 = [1], root2 = [1,2] Output: [2,2] Constraints: The number of nodes in both trees is in the range [0, 2000]. -104 <= Node.val <= 104

Explanation

Here's the breakdown of the solution:

  • Recursive Merging: Traverse both trees simultaneously using recursion. At each step, create a new node in the merged tree.
  • Value Summation: If both nodes exist at a given position, sum their values for the new node's value.
  • Node Adoption: If only one node exists, use that node as is in the merged tree. If both nodes are null, return null.

  • Time and Space Complexity: O(min(m, n)) where m and n are the number of nodes in root1 and root2 respectively, due to the recursion stopping at the smaller tree's extent. In the worst case, the space complexity can be O(min(H1, H2)) where H1 and H2 are the heights of the trees root1 and root2, due to the recursive call stack. In the best case, where the trees are balanced, it becomes O(log(min(m,n))).

Code

    class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def mergeTrees(root1: TreeNode, root2: TreeNode) -> TreeNode:
    """
    Merges two binary trees.

    Args:
        root1: The root of the first binary tree.
        root2: The root of the second binary tree.

    Returns:
        The root of the merged binary tree.
    """

    if not root1:
        return root2
    if not root2:
        return root1

    merged_node = TreeNode(root1.val + root2.val)
    merged_node.left = mergeTrees(root1.left, root2.left)
    merged_node.right = mergeTrees(root1.right, root2.right)

    return merged_node

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Merge Two Binary Trees