#include <iostream>
using namespace std;
typedef int T;
class bst{
struct Node{
T data;
Node* left;
Node* right;
Node(const T& d):data(d),left(),right(){}
~Node(){cout<<"~Node("<<this->data<<')'<<endl; };
};
Node* root;
typedef Node* tree;
int sz;
public:
bst():root(),sz(){}
~bst() { clear(); }
void insert(Node* pn, tree& t){
if(t==NULL){ t = pn; return; }
if(pn==NULL) return;
if(pn->data>=t->data) insert(pn, t->right);
else insert(pn, t->left);
}
void travel(tree& t){
if(t==NULL) return;
travel(t->left);
cout << t->data << ' ';
travel(t->right);
}
void insert(const T& d){
Node* pn = new Node(d);
insert(pn, root);
sz++;
}
void travel(){
travel(root);
cout<<endl;
}
void clear(tree& t){
if(t==NULL) return ;
clear(t->left);
clear(t->right);
delete t;
t=NULL;
}
void clear(){
clear(root);
sz=0;
}
tree& find(const T& d,tree& t){
if(t==NULL) return t;
if(d==t->data) return t;
if(d>t->data) return find(d,t->right);
if(d<t->data) return find(d,t->left);
}
//查找一个元素,返回bst::Node*&类型,如果找不到返回空
tree& find(const T& d){
return find(d,root);
}
bool remove(const T& d){
tree& t=find(d,root);
if(t==NULL) return false;
//左子树插入到右子树中
insert(t->left,t->right);
Node* p=t;
//右子树向上提
t=t->right;
//释放节点对象
delete p;
p=NULL;
sz--;
return true;
}
void removeAll(const T& d){
while((remove(d)));
}
void update(const T& old,const T& newd){
while(remove(old)){ insert(newd);}
}
int size(){
return sz;
}
int high(tree& t){
if(t==NULL) return 0;
int lh=high(t->left);
int rh=high(t->right);
return lh>rh?(lh+1):(rh+1);
}
int high(){
return high(root);
}
};
C++实现树结构
最新推荐文章于 2023-08-12 19:21:27 发布