本文介绍了二叉树计数叶片数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你已经具备了基本的二叉树方法的isEmpty(BT),根(BT),左(BT),右(BT)。写一个程序传递isLeaf(BT),返回true,如果二叉树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.

这是我有:

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叶子的数量

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

这是我有:

proc numLeaves(bt)
if (isEmpty(bt))
error ('The binary tree is empty.');
elseif (count left(bt) + right(bt));
return (left(bt) + 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));
}

这篇关于二叉树计数叶片数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 18:34