222. Count Complete Tree Nodes
Problem
Count the nodes of a complete binary tree (every level full except possibly the last, whose nodes are packed to the left) in less than O(n) time.
Example: [1,2,3,4,5,6] → 6
Constraints: up to 5·10⁴ nodes.
Compare the leftmost and rightmost depths. Equal ⇒ the subtree is perfect: 2^h − 1 nodes. Otherwise recurse into both children — only one side is non-perfect at each level.
Complexity: O(log² n).
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
l = r = root
hl = hr = 0
while l:
l, hl = l.left, hl + 1
while r:
r, hr = r.right, hr + 1
if hl == hr:
return (1 << hl) - 1
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
assert Solution().countNodes(make_tree([1, 2, 3, 4, 5, 6])) == 6
assert Solution().countNodes(make_tree(list(range(1, 16)))) == 15
assert Solution().countNodes(None) == 0
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int hl = 0, hr = 0;
for (TreeNode l = root; l != null; l = l.left) hl++;
for (TreeNode r = root; r != null; r = r.right) hr++;
if (hl == hr) return (1 << hl) - 1;
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
hl, hr := 0, 0
for l := root; l != nil; l = l.Left {
hl++
}
for r := root; r != nil; r = r.Right {
hr++
}
if hl == hr { // perfect tree
return 1<<hl - 1
}
return 1 + countNodes(root.Left) + countNodes(root.Right)
}