如何用C++递归来实现copy even data from the original BST

来源:互联网 发布:交淘宝保证金在哪里交 编辑:程序博客网 时间:2024/05/17 06:12

之前小编写了如何复制一棵BST,那现在小编稍微改一下,如何只复制偶数?这个问题就得在复制一棵BST的代码基础上,稍微修改一下。

有可能大家不知道什么BST。那么我先将这个BST的全名写出来,全名是binary search tree。中文名就是二叉搜索树。关于这个知识点,小编就不在这里细讲,不懂的就查资料吧!

OK! 下面就进入代码环节:

//This is the table.h file//The build and display function were already written#include<iostream>#include<cstring>#include<cctype>using namespace std;struct node{    int data;    node * left;    node * right;};  class table{    public:            //Copy the even data            void copy_even(table & to_copy);    private:            node * root;            //Copy the even data            void copy_even(node *& new_root,node * root);            void insert_data(node *& root, int num);};

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

//This is the table.cpp#include "table.h"void table::copy_even(table & to_copy){    copy_even(to_copy.root,root);}void table::copy_even(node *& new_root, node *root){    if(!root)        return;    if((root->data % 2) == 0)    {        insert_data(new_root,root->data);        copy_even(new_root,root->left);        copy_even(new_root,root->right);    }    else    {        copy_even(new_root,root->left);        copy_even(new_root,root->right);    }    return;}void table::insert_data(node *& root, int num){    if(!root)    {        root = new node;        root->data = num;        root->left = NULL;        root->right = NULL;        return;    }    if(num < root->data)        insert_data(root->left,num);    else        insert_data(root->right,num);}

下面是在主函数里进行调用这两个函数进行测试,看有没有实现了这个功能。

//This is the main.cpp file#include "table.h"int main(){    table object;    object.build();   //Builds a BST    object.display();  //display a BST    //Copy the even data    table new_tree;    object.copy_even(new_tree);    cout<<"This is new tree: "<<endl;    new_tree.display();    return 0;}

是不是感觉代码很简洁,看起来很舒服呢?

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

小编觉得大家有可能看不懂这个结果,那小编就为大家解释一下。
Level 1是表示根节点的位置,而原始的BST是有17个节点,新的BST 是有3个节点,并且新的BST的节点都是偶数。那这个就满足题目的要求。

以后小编还会继续写有关数据结构中的问题,敬请期待吧!

原创粉丝点击