Count Complete Tree Nodes - Problem
Complete Binary Tree Node Counter
You're given the root of a complete binary tree and need to count all nodes efficiently. A complete binary tree is a special type where:
• All levels are completely filled except possibly the last level
• The last level is filled from left to right
• At level h, there can be between 1 and 2h nodes
The challenge? Design an algorithm that runs in less than O(n) time - faster than visiting every node! This problem tests your ability to exploit the special properties of complete binary trees.
You're given the root of a complete binary tree and need to count all nodes efficiently. A complete binary tree is a special type where:
• All levels are completely filled except possibly the last level
• The last level is filled from left to right
• At level h, there can be between 1 and 2h nodes
The challenge? Design an algorithm that runs in less than O(n) time - faster than visiting every node! This problem tests your ability to exploit the special properties of complete binary trees.
Input: Root of a complete binary treeOutput: Total number of nodes in the tree Input & Output
example_1.py — Complete Binary Tree
$
Input:
root = [1,2,3,4,5,6]
›
Output:
6
💡 Note:
The tree has 6 nodes total. All levels are completely filled except the last level, which has nodes 4, 5, 6 filled from left to right.
example_2.py — Perfect Binary Tree
$
Input:
root = [1,2,3,4,5,6,7]
›
Output:
7
💡 Note:
This is a perfect binary tree where all levels are completely filled. The optimal algorithm can use the formula 2^h - 1 = 2^3 - 1 = 7.
example_3.py — Single Node
$
Input:
root = [1]
›
Output:
1
💡 Note:
Edge case with only one node - both simple traversal and optimized approaches return 1.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Structure
Complete binary tree fills levels left to right, top to bottom
2
Height Comparison
Compare leftmost and rightmost path lengths to detect perfect subtrees
3
Apply Formula
Perfect subtrees: use 2^h - 1. Incomplete subtrees: recurse
4
Combine Results
Sum up counts from all subtrees efficiently
Key Takeaway
🎯 Key Insight: Complete binary trees allow us to identify perfect subtrees by comparing heights, enabling mathematical counting instead of node-by-node traversal for significant time savings.
Time & Space Complexity
Time Complexity
O(n)
We visit every single node in the tree exactly once
✓ Linear Growth
Space Complexity
O(h)
Recursive call stack depth equals tree height h, which is log n for complete trees
✓ Linear Space
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
- Design an algorithm that runs in less than O(n) time complexity
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code