二叉树计算叶子数量

发布于 2024-10-16 03:54:53 字数 544 浏览 2 评论 0原文

假设您已经有了基本的二叉树过程 isempty(bt)、root(bt)、left(bt) 和 right(bt)。编写一个过程 isLeaf(bt),如果二叉树 bt 是叶节点,则返回 true,否则返回 false。

这就是我所拥有的:

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

然后编写一个过程 numLeaves(bt),它返回二叉树 bt 中的叶子数。

这就是我所拥有的:

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

请问您能更正吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

司马昭之心 2024-10-23 03:54:53

如果您不尝试自己解决这个问题,那么您将学到很少甚至什么也学不到,而只是为了那些来这里寻找答案的人:

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));
}

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));
}
情深缘浅 2024-10-23 03:54:53

这里的主要思想是使用递归:

节点拥有的叶子数量是其左子节点拥有的叶子数量与其右子节点拥有的叶子数量之和。

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.

腹黑女流氓 2024-10-23 03:54:53

正如 @jeffrey greenham 所说,我们可以使用递归

int countleaves(struct node* root){

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

}

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);
}

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文