Tensorum
LeetCode 222 · Other

Count Complete Tree Nodes

LeetCode 222 · Medium · solution, intuition & step-by-step walkthrough

count = 1 + count(left) + count(right).

MediumBinary SearchBit ManipulationTreeBinary Tree
1 msruntime · beats 6%
67.7 MBmemory · beats 100%
1approach
2accepted runs · last 14 Dec 2024

This is how I solved Count Complete Tree Nodes (LeetCode 222), a medium problem from the Other pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Counting every node recursively is the simplest correct answer: one for the root plus the counts of both subtrees.

Approach

  1. 1

    Empty → 0; leaf → 1.

  2. 2

    Otherwise 1 + both subtree counts.

How I solved it

Recursive countPythonO(n) time
class Solution:
    def countNodes(self, root):
        if root is None:
            return 0
        if root.left is None and root.right is None:
            return 1
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)
Loading the step-through…

Count Complete Tree Nodes — FAQ

What is the intuition behind Count Complete Tree Nodes?

Counting every node recursively is the simplest correct answer: one for the root plus the counts of both subtrees.

How do you solve Count Complete Tree Nodes (LeetCode 222)?

1. Empty → 0; leaf → 1. 2. Otherwise 1 + both subtree counts.

What is the time and space complexity of Count Complete Tree Nodes?

Time: O(n). Space: O(log n) for a complete tree. (Accepted approach: Recursive count.)

What are common mistakes in Count Complete Tree Nodes?

Comparing left and right heights gives O(log² n) by using completeness.