Manpreet Pangli
Manpreet Pangli

Reputation: 1

Binary Trees Count Number of Leaves

Suppose you already have the basic binary tree procedures isempty(bt), root(bt), left(bt), and right(bt). Write a procedure isLeaf(bt) that returns true if the binary tree bt is a leaf node and false if it is not.

This is what I have:

proc isLeaf(bt)
if (isEmpty(bt))
error('The binary tree is empty.');
elseif (left(bt) < right(bt))
return true;
else return false;

Then write a procedure numLeaves(bt) that returns the number of leaves in the binary tree bt.

This is what I have:

proc numLeaves(bt)
if (isEmpty(bt))
error ('The binary tree is empty.');
elseif (count left(bt) + right(bt));
return (left(bt) + right(bt);

please could you correct?

Upvotes: 0

Views: 12504

Answers (3)

ankit
ankit

Reputation: 517

As @jeffrey greenham said that we can use recursion

int countleaves(struct node* root){

 if(root!=null)
{
countleaves(root->left);
if(root->left==NULL&&root->right==NULL)
{
count++;
}
countleaves(root->right);
}

}

Upvotes: 0

Jeffrey Greenham
Jeffrey Greenham

Reputation: 1432

The main idea here is to use recursion:

The number of leaves a node has is the sum of the number of leaves its left child has, and the number of leaves its right child has.

Upvotes: 0

Jordi
Jordi

Reputation: 5908

You'll learn very little to nothing if you don't try to solve this yourself, but just for people coming here looking for an answer:

boolean isLeaf (BinaryTree bt) {
    return !isempty(bt) && isempty(left(bt)) && isempty(right(bt));
}

int numLeaves (BinaryTree bt) {
    if (isempty(bt))
        return 0;
    else if (isLeaf(bt))
        return 1;
    else
        return numLeaves(left(bt)) + numLeaves(right(bt));
}

Upvotes: 1

Related Questions