如何使用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
- 如何使用C++递归来复制一棵BST
- 如何使用C++递归来实现查找BST(Binary Search Tree)的最大高度
- 如何使用C++递归来实现在BST(Binary Search Tree)里将所有的叶子节点上的数字求和
- 如何使用Java来编译运行C文件(一)
- 如何用C++递归来删除所有的BST节点
- 如何使用C语言实现递归调用
- 每日一省之——使用递归法实现二叉查找树(BST),API齐全
- 如何使用C来扩展python功能
- 如何使用C来扩展python功能。
- 复制一棵二叉树的非递归算法
- 复制一棵二叉树的递归算法
- BST(BinarySortTree) 递归实现
- 如何用C++递归来查找BST中的根节点的inorder successor
- 如何用C++递归来实现copy even data from the original BST
- 极客开源-如何使用Java来发送一封电子邮件?
- 如何使用标准c语言来实现图像验证码
- 如何使用Visual Studio来写C程序
- 如何使用VS2008 C++/CLI 来自动化操作Excel
- centos6.5升级httpd
- java.lang.IllegalArgumentException: node to traverse cannot be null!
- 微信接口验证(php)
- 极大似然估计法
- Android安全之APK无源码动态调试
- 如何使用C++递归来复制一棵BST
- ES —(函数扩展)
- SQL--浅析,开窗函数,聚合开窗函数,排序开窗函数。
- 阿里云openMR的 使用
- DataTable添加列和行的三种方法
- C语言宏定义和几个坑
- hadoop简易集群搭建
- Hibernate 的原生sql查询转map setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
- 如何解决使用addBatch()和executeBatch()无法批量增加删除修改数据库数据等问题