如何用C++递归在BST(Binary Search Tree) 数有几个节点大于根节点的数字

小编上课时使用英文教材,所以对中文计算机词汇不是那么了解,所以,这里先表示抱歉。但是,我还是尽量使用中文计算机词汇来表达,这样有助于你们能看的懂小编在写什么。

现在,要实现在Binary Search Tree, 也就是二叉搜索树。下面小编就用BST来表示二叉搜索树,因为这样方便。关于知识点,小编就不在写了,不懂得就百度吧!

OK,现在就展示如何用C++递归来实现这个问题。

//Function prototype是写在.h文件
struct node
{
    int data;
    node * left;
    node * right;
};

class table
{
    public:
        //Count the number of nodes with data greater than the root's data in a BST
        int count_greater_root();

    private:
        //Count the number of nodes with data greater than the root's data in a BST
        //这个是专门用递归来实现的
        //也叫做recursive function
        int count_greater_root(node * root, int num);
};

//下面一部分是来实现这两个函数的
//实现函数在.cpp文件里
int table::count_greater_root()
{
    return count_greater_root(root,root->data);
}

int table::count_greater_root(node * root, int num)
{
    if(!root)
        return 0;
    if(root->data > num)
    {
        return count_greater_root(root->right,num)+count_greater_root(root->left,num) + 1;
    }
    return count_greater_root(root->left,num)+count_greater_root(root->right,num);
}

//下面是在主函数里进行调用这些函数
//主函数也是写在.cpp文件里的
int main()
{
    table object;
    int result = object.count_greater_root();
    cout<<"The result is: "<<result<<endl;

    return 0;
}

下面是展示运行结果:
这是结果展示

有可能大家对这个结果看不懂,没事小编会接触你们的疑惑的。
下面展示的是小编在白纸上根据结果的展示来描述这个BST.
这是树的结构

所以,根据这个树的形状,就可以知道比数字21大的数字一共有8个。

希望这篇文章对大家有所帮助,以后,小编还会继续写有关BST的C++递归博客送给大家。敬请期待吧!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值