Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Find Duplicate Subtrees

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "652" 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 root of a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values. Example 1: Input: root = [1,2,3,4,null,2,4,null,null,4] Output: [[2,4],[4]] Example 2: Input: root = [2,1,1] Output: [[1]] Example 3: Input: root = [2,2,2,3,null,3,null] Output: [[2,3],[3]] Constraints: The number of the nodes in the tree will be in the range [1, 5000] -200 <= Node.val <= 200

Explanation

Here's a breakdown of the solution:

  • Serialize Subtrees: Traverse the tree and serialize each subtree into a unique string representation. The serialization captures the structure and values of the subtree.
  • Hashing and Counting: Store these serialized strings in a hash map (dictionary). The count of each serialized string indicates how many times that specific subtree structure appears in the tree.
  • Identify Duplicates: If a serialized string appears more than once, it signifies a duplicate subtree. Store the root node of one instance of each such duplicate subtree in the result.

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

  • Space Complexity: O(N), primarily due to the hash map storing serialized subtrees and the space used by the recursion stack.

Code

    from typing import Optional, List

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
        """
        Finds all duplicate subtrees in a binary tree.

        Args:
            root: The root of the binary tree.

        Returns:
            A list of the root nodes of all duplicate subtrees.
        """
        subtree_counts = {}
        duplicate_roots = []

        def serialize(node: Optional[TreeNode]) -> str:
            """
            Serializes a subtree into a string representation.
            """
            if not node:
                return "#"  # Represent null node

            left_subtree = serialize(node.left)
            right_subtree = serialize(node.right)
            subtree_string = str(node.val) + "," + left_subtree + "," + right_subtree

            if subtree_string in subtree_counts:
                subtree_counts[subtree_string] += 1
                if subtree_counts[subtree_string] == 2:  # Add only once when count becomes 2
                    duplicate_roots.append(node)
            else:
                subtree_counts[subtree_string] = 1

            return subtree_string

        serialize(root)
        return duplicate_roots

More from this blog

C

Chatmagic blog

2894 posts