二叉搜索树 2

来源:互联网 发布:mac对应pin码查询网 编辑:程序博客网 时间:2024/05/29 17:28

又是二叉搜索树的前序遍历。

 

1.建树会顺序影响整棵树的形状

2.记得释放资源

3.可以用双重指针和引用优化程序。。

 

代码某些printf() 是之前设置的断点,,可以无视之

#include<iostream>using namespace std;struct BST{char ch;BST *lson,*rson;BST(){ch=0;                   //不可能的字符 lson=rson=0;}} *root;BST *insert(BST *p,char x)       //一,p不存在; 二,p存在,1.x==p->ch 2.x< 3.x>  {//printf("x=%c p==%d\n",x,p);;if(p==NULL){p=new BST;p->ch=x;return p;}//printf("~");if(x<p->ch)p->lson=insert(p->lson,x);if(x>p->ch)p->rson=insert(p->rson,x);return p;}char RE[11];int nRE;void pre_order(BST *p) //一,p存在 二,p不存在{if(p)RE[nRE++]=p->ch;//cout<<"RE="<<RE<<endl;if(p->lson) pre_order(p->lson);if(p->rson) pre_order(p->rson);}void Free(BST *p){if(p->lson) Free(p->lson);if(p->rson) Free(p->rson);delete p;}int main(){int n,i,j,len;char t[11],model[11];while(scanf("%d",&n),n){root=0;scanf("%s",t);len=strlen(t);for(i=0;i<len;i++) root=insert(root,t[i]);nRE=0;pre_order(root);RE[nRE]='\0';strcpy(model,RE);for(i=1;i<=n;i++){BST *p=0;//printf("~");scanf("%s",t);len=strlen(t);// printf("!!%s\n",t);for(j=0;j<len;j++) p=insert(p,t[j]);nRE=0;pre_order(p);RE[nRE]='\0';if(strcmp(model,RE)==0) printf("YES\n");elseprintf("NO\n");Free(p);}//printf("@");Free(root);}return 0;}