二叉搜索树的c++实现(含深复制)

来源:互联网 发布:sqlserver列名无效 编辑:程序博客网 时间:2024/05/20 05:07

本文参考了《数据结构与算法分析C++描述(第3版)》[美] Mark Weiss 著       张怀勇 等译     刘田   审校


binarynode.h:

struct binarynode{int element;binarynode * left;binarynode * right;binarynode(int e,binarynode* l,binarynode * r){element=e;left=l;right=r;}};

binarytree.h:

#include <iostream>#include "binarynode.h" using namespace std; class binarytree{private:binarynode * root;//根结点public:binarytree(){//构造函数root=NULL;}void copy(binarytree &old_tree){//实现深复制makeempty();root = clone(old_tree.root);}~binarytree(){//析构函数makeempty();}binarynode * getroot(){return root;}void print(binarynode * t,int space=-3){//以中序遍历输出二叉树if(t!=NULL){space=space+3;print(t->left,space);for(int i=0;i<space;i++)cout<<" ";cout<<t->element;cout<<endl;print(t->right,space);}}void print(){print(root);}void insert(int x,binarynode * & t){//插入元素if(t==NULL)t=new binarynode(x,NULL,NULL);else if(x<t->element)insert(x,t->left);else if(x>t->element)insert(x,t->right);else;//最后一种情况是要插入的元素已经在树中}void insert(int x){insert(x,root);}bool contain(int x,binarynode * t){//查找元素if(t==NULL)return false;else if(x<t->element)return contain(x,t->left);else if(x>t->element)return contain(x,t->right);else return true;}bool contain(int x){return contain(x,root);}binarynode * findmin(binarynode *t){//返回树的最小元素if(t==NULL)return t;else if(t->left==NULL)return t;else return findmin(t->left);}binarynode * findmin(){return findmin(root);}binarynode * findmax(binarynode *t){//返回树的最大元素if(t==NULL)return t;else if(t->right==NULL)return t;else return findmax(t->right);}binarynode * findmax(){return findmax(root);}void remove(int x,binarynode * & t){//删除元素if(t==NULL)return;else if(x<t->element)remove(x,t->left);else if(x>t->element)remove(x,t->right);//找到该元素else if(t->left==NULL){binarynode * ptr=t;t=t->right;delete ptr;}else if(t->right==NULL){binarynode * ptr=t;t=t->left;delete ptr;}else{//左右儿子都有t->element=findmin(t->right)->element;remove(t->element,t->right);}}void remove(int x){remove(x,root);}bool isempty(){//判断树是否为空return root==NULL;}void makeempty(binarynode * & t){//清空树if(t!=NULL){makeempty(t->left);makeempty(t->right);delete t;}t=NULL;}void makeempty(){makeempty(root);}binarynode * clone(binarynode * t){//复制一个新的二叉树(深复制)if(t==NULL)return NULL;binarynode * t2 =new binarynode(t->element,clone(t->left),clone(t->right));return t2;}};

主函数/简单测试函数:

#include<iostream>#include<algorithm>#include<vector>#include "binarytree.h"using namespace std;int main(){vector<int>a;for(int i=0;i<20;i++)a.push_back(i+1);random_shuffle(a.begin(),a.end());binarytree bt;for(i=0;i<a.size();i++)bt.insert(a.at(i));bt.print();cout<<"根"<<bt.getroot()<<endl;cout<<"////////////////////////"<<endl;binarytree  bt2;bt2.copy(bt);bt2.print();cout<<"根"<<bt2.getroot()<<endl;cout<<"//////"<<endl;return 0;}
部分结果截图:



0 0
原创粉丝点击