tree

Posted on 2013-04-24 13:36  xiaomaogong  阅读(151)  评论(0编辑  收藏  举报

#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"<<endl;}
};
Node* root;
typedef Node* tree;
int sz;

void clear(tree& t){
if(t==NULL) return;
clear(t->left);
clear(t->right);
delete t;
t=NULL;

}
void insert(Node* pn,tree& t){
if(pn==NULL) return;
if(t==NULL) t=pn;
else
{
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);
}

tree& find(tree& t,const T& d){
if(t==NULL) return t;
if(t->data==d) return t;
if(t->data<d) return find(t->right,d);
return find(t->left,d);
}
int high(tree& t){
if(t==NULL) return 0;
int left=high(t->left);
int right=high(t->right);
return left>right?left+1:right+1;
}
public:
bst():root(),sz(){}

void clear(){
clear(root);
sz=0;
}
~bst(){
clear();
sz=0;
}
void insert(const T& d){
Node* pn=new Node(d);
insert(pn,root);
sz++;
}
void travel(){
travel(root);
cout<<endl;
}
//查找一个元素,返回bst::Node*&类型,如果找不到返回空
tree& find(const T& d){
find(root,d);
}
//删除一个元素
bool remove(const T& d){
tree& t=find(root,d);
if(t==NULL) return false;
insert(t->left,t->right);
Node* p =t;
t = t->right;
delete p;
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 hight()
{
high(root);
}
};

int main()
{
bst t;
t.insert(4);
t.insert(3);
t.insert(6);
t.insert(9);
cout<<t.hight()<<endl;
t.travel();
cout<<t.find(1)<<endl;
t.remove(3);
t.travel();
t.update(4,5);
t.insert(12);
t.insert(34);
t.insert(5);
t.insert(6);
t.insert(5);
t.travel();
t.removeAll(5);
t.travel();
cout<<t.size()<<endl;
cout<<t.hight()<<endl;
t.clear();

}

Copyright © 2024 xiaomaogong
Powered by .NET 9.0 on Kubernetes