题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3791
给一个序列,让你判断接下来输入的n个序列是否可以生成同一个二叉树。
BFS一遍就可以了。
1 #include <algorithm> 2 #include <iostream> 3 #include <iomanip> 4 #include <cstring> 5 #include <climits> 6 #include <complex> 7 #include <fstream> 8 #include <cassert> 9 #include <cstdio> 10 #include <bitset> 11 #include <vector> 12 #include <deque> 13 #include <queue> 14 #include <stack> 15 #include <ctime> 16 #include <set> 17 #include <map> 18 #include <cmath> 19 20 using namespace std; 21 22 typedef struct Node { 23 Node* left; 24 Node* right; 25 int data; 26 Node() { left = NULL; right = NULL; } 27 }Node; 28 29 queue<Node*> q; 30 31 Node* insert(Node* cur, int data) { 32 if(cur == NULL) { 33 cur = new Node(); 34 cur->data = data; 35 return cur; 36 } 37 if(data > cur->data) { 38 cur->right = insert(cur->right, data); 39 } 40 else { 41 cur->left = insert(cur->left, data); 42 } 43 return cur; 44 } 45 46 const int maxn = 11; 47 int n; 48 char tmp[maxn]; 49 char a[maxn], b[maxn]; 50 51 void bfs(char* x) { 52 Node* root = NULL; 53 scanf("%s", tmp); 54 int len = strlen(tmp); 55 for(int i = 0; i < len; i++) { 56 root = insert(root, tmp[i]-'0'); 57 } 58 int cnt = 0; 59 while(!q.empty()) q.pop(); 60 q.push(root); 61 while(!q.empty()) { 62 Node* tmp = q.front(); 63 x[cnt++] = q.front()->data + '0'; 64 if(tmp->left) q.push(tmp->left); 65 if(tmp->right) q.push(tmp->right); 66 q.pop(); 67 } 68 } 69 70 71 int main() { 72 // freopen("in", "r", stdin); 73 while(~scanf("%d", &n) && n) { 74 memset(a, 0 , sizeof(a)); 75 memset(b, 0 , sizeof(b)); 76 bfs(a); 77 for(int i = 0; i < n; i++) { 78 bfs(b); 79 if(strcmp(a, b) == 0) { 80 printf("YES "); 81 } 82 else { 83 printf("NO "); 84 } 85 } 86 } 87 return 0; 88 }