Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Check Completeness of a Binary Tree

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "958" 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, determine if it is a complete binary tree. In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Example 1: Input: root = [1,2,3,4,5,6] Output: true Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. Example 2: Input: root = [1,2,3,4,5,null,7] Output: false Explanation: The node with value 7 isn't as far left as possible. Constraints: The number of nodes in the tree is in the range [1, 100]. 1 <= Node.val <= 1000

Explanation

Here's the breakdown of the approach and the Python code:

  • High-Level Approach:

    • Use Breadth-First Search (BFS) to traverse the tree level by level.
    • During BFS, if we encounter a None node (representing a missing node), set a flag flag to True.
    • After the flag has been set to True, if we encounter a non-None node, it means we have a node appearing after a missing node, which violates the complete binary tree property. Therefore, return False.
  • Complexity:

    • Runtime Complexity: O(N), where N is the number of nodes in the tree (BFS visits each node once).
    • Storage Complexity: O(W), where W is the maximum width of the tree (the maximum number of nodes at any level). In the worst case (a complete binary tree), W can be approximately N/2, so the space complexity can be considered O(N).

Code

    from collections import deque

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

def isCompleteTree(root: TreeNode) -> bool:
    if not root:
        return True

    queue = deque([root])
    flag = False  # Flag to indicate if we've seen a null node

    while queue:
        node = queue.popleft()

        if not node:
            flag = True
        else:
            if flag:
                return False  # Found a node after a null node
            queue.append(node.left)
            queue.append(node.right)

    return True

More from this blog

C

Chatmagic blog

2894 posts