如何使用C++递归来复制一棵BST

来源:互联网 发布:手机淘宝微淘在哪里 编辑:程序博客网 时间:2024/06/06 10:07

小编先解释一下BST的全名是什么,不然大家就不知道是什么意思。BST的全名是bianry search tree. 中文名就叫做二叉搜索树。下面,小编就用这个BST来描述二叉搜索树了,因为这样简单明了。

下面是有关在table.h 文件的函数prototype。

//This is the table.h//Need to write the wrapper function and recursive function into this file//The build and display function are always written#include<iostream>#include<csting>#include<cctype>using namespace std;struct node{    int data;    node * left;    node * right;};class table{    public:        //Make a copy of a BST        void copy(table & to_copy);    private:        node * root;        //Make a copy of a BST        void copy(node *& new_root, node * root);};

下面是table.cpp文件,是专门实现这两个函数的

//This is the table.cpp#include "table.h"void table::copy(table & new_copy){    copy(new_copy.root,root);}void table::copy(node *& new_root, node * root){    if(!root)    {        new_root = NULL;        return;    }    new_root = new node;    new_root->data = root->data;    copy(new_root->left,root->left);    copy(new_root->right,root->right);    return;}

下面是在主函数里进行调用这两个函数来进行测试,看有没有写对。

//This is the main.cpp file#include "table.h"int main(){    table object;    //Call the build function, and this function is always written    object.build();    //Call the display function, and this function is also written    object.display();    //Make a copy of a BST    table new_tree;    object.copy(new_tree);    cout<<"This is the new BST: "<<endl;    new_tree.display();    return 0; }

下面是结果的展示
结果展示

有可能大家对这个结果有点看不明白,那小编就稍微解释一下。Level 1就是根节点所在位置,那这棵树的高度是7. 而大家应该注意到”This is the new BST: “这句话,这句话就是在主函数里写的,这就能看到这棵树已经建立好了。

是不是感觉用递归来实现挺神奇的。如果大家有什么疑问或者小编哪里写的不对,指出来,小编随时欢迎!

以后还会继续写有关如何用C++递归来实现有关数据结构中的问题,敬请期待吧!

阅读全文
1 0
原创粉丝点击