二叉排序树

来源:互联网 发布:手机淘宝购物付款方式 编辑:程序博客网 时间:2024/05/18 16:13
#include<iostream>#include<malloc.h> #include<stdlib.h>#include<stack>using namespace std;class BST{protected: struct BstNode{int data;struct BstNode *leftchild,*rightchild,*pa;};private:BstNode *root;static BstNode *BuyNode( ){BstNode *s = (BstNode*)malloc(sizeof(BstNode));if(s == NULL) {printf("weiwei\n");exit(1);}s->leftchild=NULL;s->rightchild=NULL;return s;}static BstNode *BuyNode(int key ){BstNode *s = (BstNode*)malloc(sizeof(BstNode));if(s == NULL) {printf("weiwei\n");exit(1);}        s->data=key;s->leftchild=NULL;s->rightchild=NULL;return s;}static void FreeNode(BstNode *ptr){free(ptr);ptr=NULL;}    static InOrder(BstNode *ptr){std::stack<BstNode *> st;while(ptr!=NULL||!st.empty()){if(ptr!=NULL){st.push(ptr);ptr=ptr->leftchild;}else{ptr=st.top();cout<<ptr->data<<"  ";st.pop();ptr=ptr->rightchild;}}cout<<endl;}    static bool SearchBST(BstNode *T,int key,BstNode *pa,BstNode **ptr){if(T==NULL){*ptr=pa;return false;}else if(key==T->data){*ptr=T;return true;}else if(key<T->data){return SearchBST(T->leftchild,key,T,ptr);}else {return SearchBST(T->rightchild,key,T,ptr);}}static bool InsertBST(BstNode **T,int key){BstNode *p,*s;if(!SearchBST(*T,key,NULL,&p)){s=BuyNode(key);if(p==NULL) *T=s;else if(key<p->data)p->leftchild=s;elsep->rightchild=s;return true;}elsereturn false;}static bool Delete(BstNode **T){BstNode *tmp,*s;if((*T)->rightchild==NULL){             tmp=*T; (*T)=(*T)->leftchild; free(tmp);}else if((*T)->leftchild==NULL){tmp=*T;(*T)=(*T)->rightchild;free(tmp);}else{tmp=(*T);s=(*T)->leftchild;while(s->rightchild){tmp=s;s=s->rightchild;}(*T)->data=s->data;if(tmp!=*T){tmp->rightchild=s->leftchild;}else{tmp->leftchild=s->leftchild;}free(s);}return true;}static bool DeleteBST(BstNode * *T,int key){if(!*T){            return false;}else{if(key==((*T)->data))return Delete(T);else if(key<(*T)->data)     return DeleteBST(&(*T)->leftchild,key);else return DeleteBST(&(*T)->rightchild,key);}}public:BST():root(NULL){}BST(int *arr,int len):root(NULL){int i=0;while(i<len){InsertBST(&root,arr[i++]);}}void DeleteBST(int key){DeleteBST(&root,key);}void InOrder(){InOrder(root);}};void main(){int arr[10]={1,245,49,3954,83,345,94,2,6,0};int len=sizeof(arr)/sizeof(arr[0]);BST mytree1(arr,len);mytree1.InOrder();mytree1.DeleteBST(94);mytree1.InOrder();}

0 0
原创粉丝点击