问题
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?
回答1:
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));
}
回答2:
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.
回答3:
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);
}
}
来源:https://stackoverflow.com/questions/4932235/binary-trees-count-number-of-leaves