//问题 C : 算法9-5~9-8:二叉排序树的基本操作 #include <stdio.h> #include <stdlib.h> typedef struct node { int key; struct node *LChild,*RChild; }BSTNode,*BSTree; void CreatBST(BSTree *bst,int n); //创建 BSTree SearchBST(BSTree bst,int key) ; //查找 void InsertBST(BSTree *bst,int key) ; //插入 BSTNode * DelBST(BSTree t,int k) ; //删除 void print_bst(BSTree t) //输出 { if (!t) { print_bst(t->LChild); printf("\t%d\t", t->key); print_bst(t->RChild); } } /*Creat new tree*/ void CreatBST(BSTree *bst,int n) { int i; int key; *bst=NULL; for(i=1;i<=n;i++) { scanf("%d",&key); InsertBST(bst,key); } //return bst; } /*Search*/ BSTree SearchBST(BSTree bst,int key) { if(!bst) //空树 return NULL; else if(bst->key==key) //找到则返回 return bst; else if(key <bst->key) //小于当前值 return SearchBST(bst->LChild, key); //搜索左子树 else return SearchBST(bst->RChild, key); } /*Insert*/ void InsertBST(BSTree *bst,int key) { BSTree t; if(*bst==NULL) //空树,创建 { t=(BSTree)malloc(sizeof(BSTNode)); t->key=key; t->LChild=NULL; t->RChild=NULL; *bst=t; } else if(key <(*bst)->key) //小于当前值 InsertBST(&((*bst)->LChild),key); //插入到左子树 else if(key>(*bst)->key) InsertBST(&(*bst)->RChild,key); } /*Delet*/ BSTNode *DelBST(BSTree t,int k) { BSTNode *p,*f,*s,*q; p=t; f=NULL; while(p) { if(p->key==k) //先找到删除元素在树中的位置,遍历根,左子,右子 break; f=p; if(p->key>k) p=p->LChild; else p=p->RChild; } if(p==NULL) //没有左右子树 return t; if(p->LChild==NULL) //左子树为空 { if(f==NULL) t=p->RChild; else if(f->LChild==p) f->LChild=p->RChild; else f->RChild=p->LChild; free(p); } else //右子树为空 { q=p; s=s->LChild; while(s->RChild) { q=s; s=s->RChild; } if(q==p) q->LChild=s->LChild; else q->RChild=s->LChild; p->key=s->key; free(s); } return t; } /*Main*/ int main() { BSTNode *root; int data,n,k; scanf("%d",&n); scanf("%d",&k); CreatBST(&root,n); for(int j=0;j<k;j++) { scanf("%d",&data); if(SearchBST(root,data)==NULL) printf("0 "); else printf("1 ");; //if(root!=NULL) // printf("%d ",root->key); // else printf("0 "); // //print_bst(root); } } /************************************************************** Problem: 2169 User: admin Language: C Result: Accepted Time:11 ms Memory:1144 kb ****************************************************************/