二叉树
代码
#include <iostream>
using namespace std;
typedef int T;
class bst{
struct Node{
T data;
Node* L;
Node* R;
Node(const T& d = T(), Node* l = NULL, Node* r = NULL):data(d),L(l),R(r){}
};
typedef Node* Tree;
Node* rp;
int n;
Tree Null;
public:
bst():rp(),n(),Null(NULL){}
~bst(){clear();}
bst& insert(const T& d){
insert(rp, new Node(d));
++n;
return *this;
}
void insert(Tree& t, Node* p){
if (t==NULL){
t = p;
} else if (p->data < t->data) {
insert(t->L, p);
} else {
insert(t->R, p);
}
}
bool remove(const T& d){
Tree& t = find(d);
if (t==NULL){
return false;
}
Tree p = t;
if (t->L!=NULL) {
insert(t->R, t->L);
}
t = t->R;
delete p;
--n;
return true;
}
Tree& find(const T& d){
return find(rp, d);
}
Tree& find(Tree& t, const T& d){
if (t==NULL){
return Null;
} else if (d==t->data){
return t;
} else if (d<t->data){
return find(t->L, d);
} else {
return find(t->R, d);
}
}
void travel(){
travel(rp);
cout << endl;
}
void travel(Tree t)const{
if (t!=NULL){
travel(t->L);
cout << t->data << " ";
travel(t->R);
}
}
void clear(){clear(rp);n=0;}
void clear(Tree& t){
if (t!=NULL){
clear(t->L);
clear(t->R);
delete t;
t = NULL;
}
}
int hight(){
return hight(rp);
}
int hight(Tree t){
if (t == NULL){
return 0;
}
int lh = hight(t->L);
int rh = hight((t->R));
return 1+(lh>rh?lh:rh);
}
bool empty()const{
return rp == NULL;
}
int size()const{
return n;
}
};
int main (){
bst b;
b.insert(4).insert(2).insert(5);
b.insert(1).insert(6);
b.travel();
b.insert(3);
b.travel();
b.remove(2);
b.travel();
cout << b.hight();
getchar();
return 0;
}