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
Count Complete Tree Nodes: Input → Process → OutputInput: Complete Tree123456Process: Smart Algorithm1. Calculate height = 22. Binary search last level3. Count = 2² + 2 = 6Output: Total Count6nodes countedNaive: O(n) - visit each nodeOptimal: O(log² n) - use complete tree structureKey insight: Complete tree allows efficient counting without visiting all nodes
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
Asked in
Google 12 Facebook 8 Amazon 6 Microsoft 5
78.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen