Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count leaf nodes in a binary tree

Count how many leaf nodes (nodes with no children) are present in a binary tree.

Python practice7 minTrees & Binary TreesBeginnerLast updated March 29, 2026

Problem statement

Given the root of a binary tree, return the number of leaf nodes in the tree. A leaf node is a node with no left and no right child. If the tree is empty, return 0. Implement count_leaves(root) to return the integer count.

Task

Write a function to count the number of leaves in a binary tree.

Examples

Two leaves

Input

count_leaves(TreeNode(1, TreeNode(2), TreeNode(3)))

Output

2

Nodes 2 and 3 are leaves.

Input format

A single argument: root (TreeNode or None).

Output format

An integer: number of leaf nodes.

Constraints

- Tree size up to a few thousand nodes. - Use recursion or iterative traversal.

Samples

Sample 1

Input

count_leaves(None)

Output

0

Empty tree has zero leaves.