Count Complete Tree Nodes — LeetCode 222 Python Solution

EasyBit ManipulationTreeBinary SearchBinary Tree
Problem
#222
Reading time
2 min

The problem

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.

Example

Input
root = [1,2,3,4,5,6]
Output
6

Python solution

Python
# 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
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the tree auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 222. Count Complete Tree Nodes is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 222. Count Complete Tree Nodes?
LeetCode 222. Count Complete Tree Nodes is rated Easy on LeetCode.
What is the time complexity of LeetCode 222. Count Complete Tree Nodes?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 222. Count Complete Tree Nodes?
The Python solution on this page uses O(n), where n is the number of nodes in the tree auxiliary space.
What topics does LeetCode 222. Count Complete Tree Nodes cover?
LeetCode 222. Count Complete Tree Nodes is tagged Bit Manipulation, Tree, Binary Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview