
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)
Editorial
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. |
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