Count Complete Tree Nodes - Problem
Given the root of a complete binary tree, return the number of nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2^h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
Input & Output
Example 1 — Complete Binary Tree
$
Input:
root = [1,2,3,4,5,6]
›
Output:
6
💡 Note:
All levels are filled except the last level has 3 out of 4 possible nodes, total count is 6
Example 2 — Single Node
$
Input:
root = [1]
›
Output:
1
💡 Note:
Tree has only root node, so count is 1
Example 3 — Perfect Binary Tree
$
Input:
root = [1,2,3,4,5,6,7]
›
Output:
7
💡 Note:
All levels are completely filled, total 7 nodes in perfect binary tree
Constraints
- The number of nodes in the tree is in the range [1, 2 × 104]
- 1 ≤ Node.val ≤ 5 × 104
- The tree is guaranteed to be complete
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Complete binary tree with nodes filled left-to-right
2
Smart Counting
Use complete tree properties instead of visiting each node
3
Result
Total count calculated efficiently
Key Takeaway
🎯 Key Insight: Use the complete binary tree property to count nodes efficiently with binary search instead of traversing every node
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code