以下為二叉查找樹(中序遍歷)其它的樓主應該是能寫了吧:
typedef int T;
class Bst{
struct Node{
T data;
Node* L;
Node* R;
Node(const T& d):data(d),L(0),R(0){}
};
typedef Node* TreeRoot;
Node* root;
int len;
public:
Bst():root(NULL),len(0){}
~Bst(){Clear(root);}
bool Empty()const{return len==0;}
int Size()const{return len;}
private:
void Ins(TreeRoot& r, Node* p){
if(r==NULL) r=p;
else if(p->data < r->data) Ins(r->L,p);
else Ins(r->R,p);
}
bool Erase(TreeRoot& r, const T& d){
Node*& t = Find(r,d);
if(t==NULL) return false;
if(t->L!=NULL) Ins(t->R, t->L);//左子樹根節點插入右子樹
Node* p = t;
t = t->R;
delete p;
return true;
}
Node*& Find(TreeRoot& r, const T& d){
if(r==NULL) return r;//此時r為空,表示失敗
if(r->data==d) return r;//此時r指向找到的數據,查找成功
if(d < r->data) return Find(r->L,d);
return Find(r->R,d);
}
void Travel(TreeRoot& r){
if(r==NULL) return;
Travel(r->L);
cout << r->data << ' ';
Travel(r->R);
}
void Clear(TreeRoot& r){
if(r==NULL) return;
Clear(r->L);
Clear(r->R);
delete r;
r = NULL;
}
public:
bool Replace(const T& oldd, const T& newd){
if(!Erase(root,oldd)) return false;
Ins(root,new Node(newd));
return true;
}
void Ins(const T& d){Ins(root,new Node(d));++len;}
void Travel(){Travel(root);cout<<endl;}
bool Erase(const T& d){return Erase(root,d);--len;}
bool Find(const T& d){return Find(root,d)!=NULL;}
void Clear(){Clear(root);}
};
int main()
{
Bst b;
b.Ins(20);b.Ins(10);b.Ins(30);b.Ins(15);b.Ins(8);
b.Ins(50);b.Ins(25);
cout << "size=" << b.Size() << endl;
b.Travel();
b.Replace(25,18);b.Replace(10,22);b.Replace(20,35);
cout << "size=" << b.Size() << endl;
b.Travel();
}