Tutorialspoint
Problem
Solution
Submissions

Complete Tree Nodes

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to count the number of nodes in a complete binary tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. The program should efficiently count nodes without traversing every node.

Example 1
  • Input: Tree with nodes [1,2,3,4,5,6]
  • Tree structure:




  • Output: 6
  • Explanation: The tree has 6 nodes in total. It's a complete binary tree with all levels filled except the last. Therefore, the count is 6.
Example 2
  • Input: Empty tree
  • Output: 0
  • Explanation: The tree is empty (root is NULL). An empty tree has 0 nodes. Therefore, the count is 0.
Constraints
  • The number of nodes in the tree is in the range [0, 5 * 10^4]
  • 0 ≤ Node.val ≤ 5 * 10^4
  • The tree is guaranteed to be complete
  • Time Complexity: O(log^2 n)
  • Space Complexity: O(log n)
Binary TreeTreeFacebookAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the property of complete binary trees to optimize counting
  • Calculate the height of the leftmost and rightmost paths
  • If both heights are equal, the tree is a perfect binary tree with 2^h - 1 nodes
  • If heights differ, recursively count nodes in left and right subtrees
  • Use bit manipulation to calculate powers of 2 efficiently
  • The height can be found by going as far left as possible

Steps to solve by this approach:

 Step 1: Handle the base case where root is NULL, return 0
 Step 2: Calculate the height by going as far left as possible from root
 Step 3: Calculate the height by going as far right as possible from root
 Step 4: If both heights are equal, the tree is perfect with 2^h - 1 nodes
 Step 5: If heights differ, recursively count nodes in left and right subtrees
 Step 6: Return 1 (current node) plus the sum of left and right subtree counts
 Step 7: Use bit shifting (1 << h) to efficiently calculate powers of 2

Submitted Code :