Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: K-th Largest Perfect Subtree Size in Binary Tree

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3319" 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 the root of a binary tree and an integer k. Return an integer denoting the size of the kth largest perfect binary subtree, or -1 if it doesn't exist. A perfect binary tree is a tree where all leaves are on the same level, and every parent has two children. Example 1: Input: root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2 Output: 3 Explanation: The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are [3, 3, 1, 1, 1, 1, 1, 1]. The 2nd largest size is 3. Example 2: Input: root = [1,2,3,4,5,6,7], k = 1 Output: 7 Explanation: The sizes of the perfect binary subtrees in non-increasing order are [7, 3, 3, 1, 1, 1, 1]. The size of the largest perfect binary subtree is 7. Example 3: Input: root = [1,2,3,null,4], k = 3 Output: -1 Explanation: The sizes of the perfect binary subtrees in non-increasing order are [1, 1]. There are fewer than 3 perfect binary subtrees. Constraints: The number of nodes in the tree is in the range [1, 2000]. 1 <= Node.val <= 2000 1 <= k <= 1024

Explanation

Here's a solution to the problem, with explanations and the code.

  • Identify Perfect Subtrees: Traverse the binary tree in a post-order manner. For each node, determine if the subtree rooted at that node is a perfect binary tree.
  • Calculate Size and Store: If a subtree is perfect, calculate its size (number of nodes) and store it in a list.
  • Find Kth Largest: Sort the list of perfect subtree sizes in descending order. Return the element at index k-1 if it exists; otherwise, return -1.

  • Runtime Complexity: O(N log N), where N is the number of nodes in the tree due to the sorting step. The tree traversal itself is O(N).

  • Storage Complexity: O(N) in the worst case, to store the sizes of all perfect subtrees.

Code

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

def kthLargestPerfectBinarySubtree(root, k):
    """
    Finds the size of the kth largest perfect binary subtree in a given binary tree.

    Args:
      root: The root of the binary tree.
      k: An integer representing the kth largest perfect binary subtree to find.

    Returns:
      The size of the kth largest perfect binary subtree, or -1 if it doesn't exist.
    """

    perfect_subtree_sizes = []

    def is_perfect(node):
        """
        Checks if a binary tree is perfect.
        """
        if not node:
            return 0

        def get_height(node):
          if not node:
            return 0
          return 1 + get_height(node.left)

        height = get_height(node)

        def is_perfect_recursive(node, h):
            if not node:
                return True

            if not node.left and not node.right:
              return h == 1

            if not node.left or not node.right:
              return False

            return is_perfect_recursive(node.left, h-1) and is_perfect_recursive(node.right, h-1)

        return is_perfect_recursive(node, height)

    def get_size(node):
        """
        Calculates the size of a binary tree (number of nodes).
        """
        if not node:
            return 0
        return 1 + get_size(node.left) + get_size(node.right)

    def postorder(node):
        """
        Performs a post-order traversal of the binary tree.
        """
        if not node:
            return

        postorder(node.left)
        postorder(node.right)

        if is_perfect(node):
            perfect_subtree_sizes.append(get_size(node))

    postorder(root)

    perfect_subtree_sizes.sort(reverse=True)

    if k <= len(perfect_subtree_sizes):
        return perfect_subtree_sizes[k - 1]
    else:
        return -1

More from this blog

C

Chatmagic blog

2894 posts