二叉搜索树
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3420 Accepted Submission(s): 1496Problem Description判断两序列是否为同一二叉搜索树序列Input开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。Output如果序列相同则输出YES,否则输出NOSample Input25674325432675763420Sample OutputYES NOSource
搜索二叉数的定义:
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
不算什么难题,纯粹的数据结构,二叉树的建立与遍历,就是注意下应该按照搜索二叉树的定义进行建树,然后将建立出来的树比较一下对应位置的数值是否相等即可。
1 #include<iostream> 2 #include<vector> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include<algorithm> 7 8 using namespace std; 9 struct nodes 10 { 11 int date; 12 struct nodes *left,*right; 13 }*tree,*cur; 14 struct nodes *Creat(int x) 15 { 16 cur = (struct nodes *)malloc(sizeof(struct nodes)); 17 cur->left = NULL; 18 cur->right = NULL; 19 cur->date = x; 20 return cur; 21 }; 22 struct nodes *build(int x,struct nodes *root) 23 { 24 if(root == NULL) 25 { 26 root = Creat(x); 27 } 28 else 29 { 30 if(x <= root->date) 31 root->left = build(x,root->left); 32 else 33 root->right = build(x,root->right); 34 } 35 return root; 36 } 37 int cnt; 38 void lookthrough(struct nodes *root,int digit[]) 39 { 40 if(root != NULL) 41 { 42 digit[cnt++] = root->date; 43 lookthrough(root->left,digit); 44 lookthrough(root->right,digit); 45 } 46 } 47 int main(void) 48 { 49 int n,i,j,a[25],b[25],l; 50 char str[25]; 51 while(scanf("%d",&n),n) 52 { 53 scanf("%s",str); 54 tree = Creat(str[0]-'0'); 55 l = strlen(str); 56 for(i = 1; i < l; i++) 57 { 58 tree = build(str[i]-'0',tree); 59 } 60 cnt = 0; 61 lookthrough(tree,a); 62 63 for(i = 0; i < n; i++) 64 { 65 tree = NULL; 66 scanf("%s",str); 67 tree = Creat(str[0] - '0'); 68 for(j = 1; j < l; j++) 69 { 70 tree = build(str[j]-'0',tree); 71 } 72 cnt = 0; 73 lookthrough(tree,b); 74 int ans = 1; 75 for(j = 0; j < l; j++) 76 if(a[j] != b[j]) 77 { 78 ans = 0; 79 break; 80 } 81 82 if(ans == 0) 83 printf("NO "); 84 else 85 printf("YES "); 86 } 87 } 88 return 0; 89 }