Add the following recursive method to your binary tree's node class:
size_t Node::count_leaves()
{
if (!left && !right) return 1; // this node is a leaf
size_t count = 0;
if (left) count += left-count_leaves(); // count leaves on left
if (right) count += right-leaves(); // count leaves on right;
return count; // return total leaves.
}
To count the leaves of the entire tree, call the method on the root node of the tree. To count the leaves of a subtree, call the method on the root node of the subtree.
Copyright © 2026 eLLeNow.com All Rights Reserved.