Count Complete Tree Nodes
Given the root of a complete binary tree, return the number of the 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 2h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [1]
Output: 1
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.
Brute Force Approach: DFS (O(n))
Just do any traversal and count nodes.
❌ Why not optimal?
-
It's O(n) time → may be too slow for large trees (up to 10⁵ nodes)
-
Doesn’t use the complete tree property
Optimal Approach: Use Binary Tree Height Trick (O(log²n))
💡 Key Insight:
In a complete binary tree:
-
If left height = right height, it is a perfect binary tree → total nodes =
2^h - 1
-
Otherwise, recursively count in left & right.
🔁 Steps:
-
Get leftmost height of left subtree
-
Get rightmost height of right subtree
-
If heights are equal, it's a perfect subtree → use formula
-
If not equal → recursively count nodes in left and right
Comments
Post a Comment