二叉树插入、删除、排序、查找等算法——经典算法及应用实例
1 #include <iostream> 2 using namespace std; 3 #include <iomanip> 4 typedef char T; 5 class bst{ 6 struct Node{ 7 T data; 8 Node* L; 9 Node* R; 10 Node(const T& d):data(d),L(),R(){} 11 Node(const T& d,Node*l,Node*r):data(d),L(l),R(r){} 12 }; 13 typedef Node* tree; 14 Node* rp; 15 int n; 16 public: 17 bst():rp(),n(){} 18 void clear(){clear(rp);n=0;} 19 ~bst(){clear();} 20 void insert(const T& d){insert(rp,new Node(d));++n;} 21 tree& find(const T& d){return find(rp,d);} 22 void travel()const{travel(rp);cout<<endl;} 23 bool empty()const{return rp==NULL;} 24 bool remove(const T& d){ 25 tree& t = find(d); 26 if(t==NULL) return false; 27 Node* p = t; 28 if(t->L!=NULL) insert(t->R, t->L); 29 t = t->R; 30 delete p; 31 --n; 32 return true; 33 } 34 const T& root()const{if(!rp) throw"空";return rp->data;} 35 int size()const{return n;} 36 void update(const T& olddata,const T& newdata){ 37 if(remove(olddata)) insert(newdata); 38 } 39 void insert(tree& t, Node* p){ 40 if(t==NULL) t = p; 41 else if(p->data < t->data) insert(t->L,p); 42 else insert(t->R,p); 43 } 44 tree& find(tree& t, const T& d){//返回以d为根的子树的根指针 45 if(t==NULL) return t;//没找到 46 else if(d==t->data) return t;//找到了 47 else if(d<t->data) return find(t->L,d); 48 else return find(t->R,d); 49 } 50 void travel(tree t)const{ 51 if(t!=NULL){ 52 travel(t->L); 53 cout << t->data << ' '; 54 travel(t->R); 55 } 56 } 57 void clear(tree& t){ 58 if(t!=NULL){ 59 clear(t->L); 60 clear(t->R); 61 delete t; t=NULL; 62 } 63 } 64 int high(tree t){ 65 if(t==NULL) return 0; 66 int lh = high(t->L); 67 int rh = high(t->R); 68 return 1+(lh>rh?lh:rh); 69 } 70 void print(tree t, int space, char sign){ 71 if(t==NULL) return; 72 print(t->R,space+3,'/'); 73 cout << setw(space+1) << sign << t->data << endl; 74 print(t->L,space+3,'\\'); 75 } 76 void print(){ print(rp,0,'*');cout<<"---------"<<endl; } 77 }; 78 int main() 79 { 80 bst b; 81 b.insert('k');b.insert('s');b.insert('f');b.insert('t'); 82 b.insert('a');b.insert('m');b.insert('x');b.insert('e'); 83 b.insert('w');b.insert('b');b.insert('u');b.insert('j'); 84 b.print(); 85 b.remove('k');b.remove('m');b.remove('j');b.remove('u'); 86 b.print(); 87 b.update('b','k');b.update('k','b');b.update('x','*'); 88 b.print(); 89 while(!b.empty()) b.remove(b.root()); 90 cout<<"size:"<<b.size()<<endl; 91 b.print(); 92 }