Program to count number of leaf node in binary tree in c plus plus?

1 answer

Answer

1013751

2026-05-09 13:00

+ Follow

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.

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.