<hdu

  这里是杭电上的链接http://acm.hdu.edu.cn/showproblem.php?pid=3791

  Problem Description:
  判断两序列是否为同一二叉搜索树序列
 Input:
  开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
  接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
  接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
  Output:
  如果序列相同则输出YES,否则输出NO
 Sample Input:
  2
  567432
  543267
  576342
  0
  Sample Output:
  YES
  NO
 
   解题思路一方面不知道怎么限制输入,另一方面,给出的例子中输入没有空格。只有选择字符数组输入了,就这里有一点小技巧,别的地方都是常规思路。
  这里是代码:
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 using namespace std;
 6 
 7 struct node {
 8     int val;
 9     node *lch;
10     node *rch;
11 };
12 
13 node *creat (node *p, int x) {
14         if (p == NULL) {
15             node *q = new node;
16             q->val = x;
17             q->lch = q->rch = NULL;
18             return q;
19         }
20         else {
21             if (x < p->val) p->lch = creat (p->lch,x);
22             else p->rch = creat (p->rch,x);
23             return p;
24         }
25 }
26 int flag;
27 int pre_order (node *s1,node *s2) {
28     if (s1 && s2) {////如果只是一个s1交上去说是运行错误
29         if(s1->val != s2->val) {
30             flag = 0;
31             return flag;
32         }
33         pre_order (s1->lch,s2->lch);
34         pre_order (s1->rch,s2->rch);
35     }
36     return flag;
37 }
38 
39 int main() {
40     int n;
41     char a[20];
42     char b[20];
43     while (cin >> n && n) {
44         node *root1 = NULL;
45         scanf ("%s",a);
46         int len = strlen (a);
47         for (int i = 0; i < len; ++i) {
48             int x = a[i] - '0';
49             root1 = creat(root1,x);
50         }
51         while (n--) {
52             flag = 1;
53             node *root2 = NULL;
54             scanf ("%s",b);
55             int len = strlen (b);
56             for (int i = 0; i < len; ++i) {
57                 int x = b[i] - '0';
58                 root2 = creat(root2,x);
59             }
60             if (pre_order (root1,root2))
61                 cout << "YES
";
62             else
63                 cout << "NO
";
64         }
65     }
66     return 0;
67 }
View Code

  欢迎码友评论,一起成长。

原文地址:https://www.cnblogs.com/Ddlm2wxm/p/5704685.html