Skip to content

Count Complete Tree Nodes

Given the root of a complete binary tree, return the number of the nodes in the tree.

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible.

InputOutputExplanation
[1,2,3,4,5,6]6All 6 nodes present in complete tree
[1,2,3,4,5,6,7]7Perfect binary tree of height 2
  • The number of nodes is in the range [1, 5 * 10^4].
  • 0 <= Node.val <= 100
ApproachTimeSpaceBest When
Level CalculationO(log² n)O(log n)Direct height comparison intuitive
Binary SearchO(log² n)O(log n)Explicit search on position space
★ Recommended

Calculate left and right subtree heights. If equal, left is perfect; otherwise, right is perfect. Use formula 2^h - 1 for perfect subtrees.

⏱ Time O(log² n) Recursive depth × height calculation 💾 Space O(log n) Recursion stack
function countNodes(root):
if not root: return 0
leftHeight = countLeftDepth(root)
rightHeight = countRightDepth(root)
if leftHeight == rightHeight:
return (2^(leftHeight+1) - 1) + countNodes(root.right)
else:
return (2^(rightHeight+1) - 1) + countNodes(root.left)
count_complete_tree_nodes_level_calculation.py
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def countNodes(root: Optional[TreeNode]) -> int:
"""
Count nodes in complete binary tree using level calculation.
For complete tree, if left height == right height, left is perfect.
Time: O(log² n), Space: O(log n) for recursion
"""
if not root:
return 0
# Calculate left and right heights
left_height = 0
left_node = root.left
while left_node:
left_height += 1
left_node = left_node.left
right_height = 0
right_node = root.right
while right_node:
right_height += 1
right_node = right_node.right
if left_height == right_height:
# Left subtree is perfect: 2^h - 1 nodes + root + recursively count right
return (1 << (left_height + 1)) - 1 + countNodes(root.right)
else:
# Right subtree is perfect: 2^h - 1 nodes + root + recursively count left
return (1 << (right_height + 1)) - 1 + countNodes(root.left)
# Test cases
if __name__ == "__main__":
# Example 1: Complete tree with 5 nodes
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(f"Example 1 node count: {countNodes(root)}") # 5
# Example 2: Single node
single = TreeNode(1)
print(f"Example 2 node count: {countNodes(single)}") # 1
# Example 3: Empty tree
print(f"Example 3 node count: {countNodes(None)}") # 0
alternative

For complete tree of height h, search for the last node position. Use existence check to binary search the position space [2^(h-1), 2^h - 1].

⏱ Time O(log² n) Binary search × traversal to position 💾 Space O(log n) Recursion stack
count_complete_tree_nodes_binary_search.py
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def countNodes(root: Optional[TreeNode]) -> int:
"""
Count nodes in complete binary tree using binary search on node positions.
Uses existence check for node at each possible position.
Time: O(log² n), Space: O(log n) for recursion
"""
if not root:
return 0
# Find height of tree
height = 0
node = root
while node:
height += 1
node = node.left
# Binary search on number of nodes
# For a complete tree of height h, nodes range from 2^(h-1) to 2^h - 1
low = 1 << (height - 1) # 2^(h-1)
high = (1 << height) - 1 # 2^h - 1
def exists(pos, height, root):
"""Check if node at position pos exists (0-indexed, 1-based actual position)."""
left, right = 0, (1 << (height - 1)) - 1
for _ in range(height - 1):
mid = (left + right + 1) // 2
if pos >= mid:
root = root.right
left = mid
else:
root = root.left
right = mid - 1
return root is not None
while low <= high:
mid = (low + high + 1) // 2
if exists(mid, height, root):
low = mid
else:
high = mid - 1
return low
# Test cases
if __name__ == "__main__":
# Example 1: Complete tree with 5 nodes
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(f"Example 1 node count: {countNodes(root)}") # 5
# Example 2: Single node
single = TreeNode(1)
print(f"Example 2 node count: {countNodes(single)}") # 1
# Example 3: Empty tree
print(f"Example 3 node count: {countNodes(None)}") # 0
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
count_complete_tree_nodes_space_optimized.py
"""
Solution for Count Complete Tree Nodes
"""
def solve():
"""Implementation for approach 3 of Count Complete Tree Nodes"""
pass
if __name__ == "__main__":
print("Solution ready")