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 Complete Binary Tree: 1 2 3 4 5 6 root = [1,2,3,4,5,6] h=0 h=1 h=2 Height h = 2 Nodes: 1 to 2^(h+1)-1 ALGORITHM STEPS 1 Get Left Height Go left until null leftH = 3 (0,1,2) 2 Get Right Height Go right until null rightH = 2 (0,1) 3 Compare Heights If equal: 2^h - 1 If not: recurse 4 Binary Search 1 + count(left) + count(right) Time Complexity: O(log^2 n) log n height checks FINAL RESULT Counting Process: 6 3 2 1 1 1 1 + 3 + 2 = 6 Output: 6 [OK] 6 nodes counted in O(log^2 n) time Key Insight: In a complete binary tree, if left and right heights are equal, it's a perfect subtree with 2^h - 1 nodes. This allows us to skip counting nodes in perfect subtrees, achieving O(log^2 n) instead of O(n). We use binary search property: at least one subtree is always perfect at each level. TutorialsPoint - Count Complete Tree Nodes | Optimal Solution
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