Count Complete Tree Nodes Problem
Description
LeetCode Problem 222.
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 2^h 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 * 10^4].
- 0 <= Node.val <= 5 * 10^4
- The tree is guaranteed to be complete.
Solution
Approach: Compare Subtree Heights
Visiting every node takes O(n) time. A complete tree lets us skip most of them, because a perfect binary tree of height h has exactly 2h - 1 nodes and can be counted without visiting it.
The height of a complete tree is the length of its leftmost path, since the last level is filled from the left. Compute it for both subtrees of the root, leftHeight and rightHeight:
leftHeight == rightHeight: the last level reaches into the right subtree, so the left subtree's last level is full and it is perfect. Its 2leftHeight - 1 nodes plus the root give 2leftHeight. Count the right subtree recursively.leftHeight > rightHeight: the last level ends inside the left subtree, so the right subtree is perfect with heightrightHeight. Add 2rightHeight for it and the root, and count the left subtree recursively.
1 left height 2, right height 2:
/ \ the left subtree {2, 4, 5} is perfect, 2^2 = 4 nodes with the root,
2 3 then count the right subtree {3, 6}
/ \ /
4 5 6
Each step goes down one level and only recurses into one subtree, and the height checks take O(h) per level.
Complexity: O(log2 n) time, where n is the number of nodes: O(log n) levels, each with an O(log n) height check. O(log n) space for the recursion.
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
left_height = self.height_of_left_path(root.left)
right_height = self.height_of_left_path(root.right)
if left_height == right_height:
# The last level reaches the right subtree, so the left subtree is perfect:
# 2^left_height - 1 nodes, plus 1 for root.
return (1 << left_height) + self.countNodes(root.right)
# The last level ends inside the left subtree, so the right subtree is perfect
# (one level shorter): 2^right_height - 1 nodes, plus 1 for root.
return (1 << right_height) + self.countNodes(root.left)
def height_of_left_path(self, node: Optional[TreeNode]) -> int:
"""Number of levels, found by walking down the leftmost path."""
height = 0
while node is not None:
height += 1
node = node.left
return height