二叉搜索树

题目描述:
判断两序列是否为同一二叉搜索树序列
输入:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出:

如果序列相同则输出YES,否则输出NO

样例输入:
2
567432
543267
576342
0
样例输出:
YES
NO

  1 #include <iostream>
  2 #include <cstdio>
  3 #include <cstdlib>
  4 #include <cmath>
  5 #include <cctype>
  6 #include <cstring>
  7 #include <vector>
  8 #include <list>
  9 #include <deque>
 10 #include <stack>
 11 #include <queue>
 12 #include <algorithm>
 13 #include <string>
 14 #include <map>
 15 #include <set>
 16 
 17 
 18 using namespace std;
 19 
 20 struct Node{
 21     char id;
 22     int lch,rch;
 23 }node[10000];
 24 
 25 int length=0;
 26 
 27 
 28 int creat_bt(int &rt,char s[])
 29 {
 30     rt=0;
 31 
 32     int i,j,k;
 33 
 34     int len=strlen(s);
 35 
 36     for(i=0;i<len;i++)
 37     {
 38         if(i==0)
 39         {
 40             rt=length++;
 41             node[rt].id=s[i];
 42             node[rt].lch=node[rt].rch=0;
 43         }
 44         else
 45         {
 46             k=rt;
 47 
 48             int fa=0;
 49             while(k)
 50             {
 51                 if(s[i]>node[k].id)
 52                 {fa=k;k=node[k].rch;}
 53                 else
 54                 {
 55                     fa=k;k=node[k].lch;
 56                 }
 57             }
 58 
 59             k=length++;
 60             node[k].id=s[i];
 61             node[k].lch=node[k].rch=0;
 62 
 63             if(node[fa].id<node[k].id)
 64             {node[fa].rch=k;}
 65             else
 66             {node[fa].lch=k;}
 67         }
 68     }
 69     return 0;
 70 }
 71 
 72 
 73 
 74 
 75 int judge(int rt1,int rt2)
 76 {
 77     if((rt1==0)&&(rt2==0))
 78         return 1;
 79     if(rt1==0)
 80         return 0;
 81     if(rt2==0)
 82         return 0;
 83 
 84     if(node[rt1].id==node[rt2].id)
 85         return judge(node[rt1].lch,node[rt2].lch)&&judge(node[rt1].rch,node[rt2].rch);
 86     else
 87     return 0;
 88 }
 89 
 90 
 91     
 92 
 93 int main()
 94 {
 95 
 96 
 97     int n;
 98     int i,j,k;
 99 
100 
101     char s1[101],s2[101];
102 
103     while(scanf("%d",&n)!=EOF)
104     {
105         if(n==0)
106             break;
107 
108         getchar();
109 
110         length=1;
111 int rt1,rt2;
112 
113 gets(s1);
114 
115         creat_bt(rt1,s1);
116 
117         while(n--)
118         {
119 
120 
121 
122         
123 
124         length=50;
125 
126         
127             gets(s2);
128 
129         creat_bt(rt2,s2);
130 
131         int tag=judge(rt1,rt2);
132         if(tag)
133         {
134             cout<<"YES"<<endl;
135         }
136         else
137         {cout<<"NO"<<endl;}
138         }
139     }
140 
141     return 0;
142 }

 

posted @ 2012-05-31 09:50  cseriscser  阅读(154)  评论(0编辑  收藏  举报