二叉树计算叶子数量
假设您已经有了基本的二叉树过程 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不尝试自己解决这个问题,那么您将学到很少甚至什么也学不到,而只是为了那些来这里寻找答案的人:
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:
这里的主要思想是使用递归:
节点拥有的叶子数量是其左子节点拥有的叶子数量与其右子节点拥有的叶子数量之和。
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.
正如 @jeffrey greenham 所说,我们可以使用递归
As @jeffrey greenham said that we can use recursion