Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count nodes in a complete binary tree

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

Python practice25 minTrees & Binary TreesAdvancedLast updated March 29, 2026

Problem statement

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. Given the root of a complete binary tree, implement the function count_nodes(root) that returns the total number of nodes in the tree. The TreeNode structure is defined as: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right Your implementation should take advantage of the complete-tree property to run faster than a naive O(n) traversal for large trees (an O((log n)^2) approach is typical). You will be given helper function build_tree(level_list) that builds a binary tree from a level-order list (use None for missing nodes). Call count_nodes(root) with the root returned by build_tree.

Task

Implement an efficient algorithm to count nodes in a complete binary tree (better than O(n) where possible), using tree depths and recursion.

Examples

Example - small complete tree

Input

root = build_tree([1, 2, 3, 4, 5, 6])\ncount_nodes(root)

Output

6

The tree has nodes with values 1..6 arranged in level order; total count is 6.

Input format

A level-order list representation of a complete binary tree is passed to build_tree, and the root is given to count_nodes(root).

Output format

An integer representing the number of nodes in the tree.

Constraints

0 <= number of nodes <= 2^31 - 1. Aim for an algorithm with time complexity O((log n)^2) and space complexity O(log n) for recursion stack.

Samples

Sample 1

Input

count_nodes(build_tree([1, 2, 3, 4, 5, 6, 7]))

Output

7

A perfect tree of height 3 (levels 0..2) has 7 nodes.