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

之前小编写了如何复制一棵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的节点都是偶数。那这个就满足题目的要求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值