hdu3791二叉搜尋樹

來源:互聯網
上載者:User

hdu3791二叉搜尋樹

 

 

又是二叉搜尋樹的前序走訪。

 

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;}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.