Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count Complete Tree Nodes

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "222" 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 complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, 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. Design an algorithm that runs in less than O(n) time complexity. Example 1: Input: root = [1,2,3,4,5,6] Output: 6 Example 2: Input: root = [] Output: 0 Example 3: Input: root = [1] Output: 1 Constraints: The number of nodes in the tree is in the range [0, 5 104]. 0 <= Node.val <= 5 104 The tree is guaranteed to be complete.

Explanation

  • Leverage Complete Binary Tree Properties: Exploit the fact that the tree is complete. Calculate the height of the left and right subtrees. If they are equal, the left subtree is a full binary tree. Otherwise, the right subtree is a full binary tree.
    • Divide and Conquer: Recursively apply this logic to subtrees. This avoids visiting every node.
    • Base Cases: Handle null trees and single-node trees to terminate recursion.
  • Runtime Complexity: O(log2n), Storage Complexity: O(log n) due to recursion depth.

Code

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

def countNodes(root: TreeNode) -> int:
    """
    Counts the number of nodes in a complete binary tree in less than O(n) time.
    """
    if not root:
        return 0

    def height(node):
        h = 0
        while node:
            h += 1
            node = node.left
        return h

    left_height = height(root.left)
    right_height = height(root.right)

    if left_height == right_height:
        # Left subtree is full, count right subtree recursively
        return (1 << left_height) + countNodes(root.right)
    else:
        # Right subtree is full, count left subtree recursively
        return (1 << right_height) + countNodes(root.left)

More from this blog

C

Chatmagic blog

2894 posts