如何用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的节点都是偶数。那这个就满足题目的要求。
以后小编还会继续写有关数据结构中的问题,敬请期待吧!
阅读全文
1 0
- 如何用C++递归来实现copy even data from the original BST
- 如何用C++递归来删除所有的BST节点
- 如何用C++递归来查找BST中的根节点的inorder successor
- 如何用C++递归的方法来将循环链表的unique data找出来
- 【C语言】如何用递归的方法实现n^k
- VIP does not relocate back to the original node starting from 10.2.0.4 and 11.1 even after the publi
- 问题:如何用递归实现数组求和?
- 如何用递归实现数组求和
- 如何用递归实现数组求和
- 如何用IIS来实现OTA下载
- 如何用FileItem来实现文件上传
- 如何用SpringBoot框架来接收multipart/form-data文件
- 如何用SpringBoot框架来接收multipart/form-data文件
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- 如何用栈实现递归与非递归的转换
- Cygwin中配置ssh服务
- python运维之路——mysql、pymysql
- c++ vector用法
- 关于smp的比赛感悟
- 使用Lombok精简java实体类代码
- 如何用C++递归来实现copy even data from the original BST
- 如何通过js处理相同时间的信息整合到一起的问题
- CSDN博客转载方法
- 机器学习入门——简单模型讲解
- HDU2352Verdis Quo
- hdu-1269-迷宫城堡-Tarjan算法-java
- 清华大学2009年机试-递推数列-1081
- 山东省第八届ACM省赛 I 题 Parity check 详解
- c++ vector erase用法