58. Count Complete Tree Nodes

58. Count Complete Tree Nodes

Medium
46.0%
2.9k
binary-searchtreebinary-tree
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

A large-scale infrastructure system organizes data in the form of a complete binary tree, where:

  • all levels are completely filled except possibly the last
  • the last level is filled from left to right

Such structures are commonly used in:

  • heap implementations
  • priority queues
  • indexing systems

The system frequently needs to count the total number of nodes. A naive traversal would take O(n) time, but due to the special structure of a complete binary tree, the system expects a more optimized solution.

Your task is to leverage the properties of a complete binary tree to compute the number of nodes efficiently.

This is a common interview problem asked in Google, Amazon, Microsoft, Meta, and other top companies.

Your Task

Given the root of a complete binary tree, return the total number of nodes in the tree.

Input Format

  • root: root node of a complete binary tree

Each node:

TreeNode { int val; TreeNode left; TreeNode right;}

Output Format

  • Integer representing total number of nodes

Examples

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

  • 0 ≤ number of nodes ≤ 100,000
  • 0 ≤ Node.val ≤ 100,000
  • Tree is complete

Loading editor...

[1,2,3,4,5,6]
6

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback