AlgoMaster Logo

Count Complete Tree Nodes

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Simple Tree Traversal

Intuition:

The most straightforward method to count all the nodes in a tree is to traverse the tree and count each node. In a normal binary tree, this approach works perfectly fine.

Steps:

  1. Use Depth-First Search (DFS) to traverse each node starting from the root.
  2. For every node visited, increment a count.
  3. The total count after the complete traversal will give the number of nodes in the tree.

Code:

2. Binary Search and Depth Calculation

Intuition: 

Given the properties of a complete tree, we can use a more efficient method leveraging the structure. The idea is to take advantage of the depth of the tree and binary search to determine missing nodes in the last level.

Steps:

  1. Calculate the depth (measured by the number of edges) of the tree using the left-most path.
  2. If the tree is empty, return 0.
  3. Otherwise, perform binary search on the last level to check if nodes exist:
    • Half of the potential nodes can be skipped at each level of the last row, providing savings.
  4. Calculate the total number of nodes using full levels and the nodes you've confirmed in the last level.

Code: