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

来源:互联网 发布:商业机构域名 编辑:程序博客网 时间:2024/06/07 01:39

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

现在,要实现在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 0
原创粉丝点击