Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Same Tree

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "100" 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

Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example 1: Input: p = [1,2,3], q = [1,2,3] Output: true Example 2: Input: p = [1,2], q = [1,null,2] Output: false Example 3: Input: p = [1,2,1], q = [1,1,2] Output: false Constraints: The number of nodes in both trees is in the range [0, 100]. -104 <= Node.val <= 104

Explanation

Here's the breakdown of the solution:

  • Recursive Comparison: The core idea is to use recursion to traverse both trees simultaneously. At each step, we compare the values of the current nodes and recursively check if the left and right subtrees are identical.
  • Base Cases: Define base cases to handle empty trees. If both nodes are None, the subtrees are identical. If only one of them is None, they are not.
  • Value Comparison: If both nodes are not None, compare their values. If the values are different, the trees are not identical.

  • Time Complexity: O(N), where N is the minimum number of nodes in the two trees.

  • Space Complexity: O(H), where H is the height of the smaller tree, due to the recursion stack. In the worst case (skewed tree), H can be N.

Code

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

def isSameTree(p: TreeNode, q: TreeNode) -> bool:
    """
    Given the roots of two binary trees p and q, write a function to check if they are the same or not.
    Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
    """
    if p is None and q is None:
        return True
    if p is None or q is None:
        return False
    if p.val != q.val:
        return False
    return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Same Tree