-
题目描述:
-
判断两序列是否为同一二叉搜索树序列
-
输入:
-
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
-
输出:
-
如果序列相同则输出YES,否则输出NO
-
样例输入:
-
2 567432 543267 576342 0
-
样例输出:
-
YES NO
-
分析:现根据输入序列,构建二叉搜索树,然后使用中序和后序,或中序和前序,遍历两个二叉树;若遍历结果相同,则是。
-
包含中序的两种遍历方式,可确定一个二叉树。
-
#include<stdio.h> #include<string.h> struct Node { Node *lChild; Node *rChild; char digit; }tree[25]; int alloc; Node * createNode() { tree[alloc].lChild=tree[alloc].rChild=NULL; return &tree[alloc++]; } Node *insert(Node *T, char c) //插入节点 { if(T==NULL) { T=createNode(); T->digit=c; return T; } else if(T->digit>c) T->lChild=insert(T->lChild,c); else if(T->digit<c) T->rChild=insert(T->rChild,c); return T; } char postAndin[25]; //后序和中序遍历序列的连接 int size; //postAndin的大小 char input[25],test[25]; //输入和测试序列 char inputResult[25],testResult[25]; //输入和测试序列的遍历结果 int n; //测试序列个数 void post_order(Node *T) { if(T->lChild) post_order(T->lChild); if(T->rChild) post_order(T->rChild); postAndin[size++]=T->digit; } void in_order(Node *T) { if(T->lChild) in_order(T->lChild); postAndin[size++]=T->digit; if(T->rChild) in_order(T->rChild); } int main() { while(scanf("%d",&n)!=EOF) { if(n==0) break; scanf("%s",&input); Node *T=NULL; int i=0; alloc=0; while(input[i]!=0) T=insert(T,input[i++]); size=0; post_order(T); in_order(T); postAndin[size]=0; //字符数组末尾加上\0 strcpy(inputResult,postAndin); //printf("原始串的后序+中序:%s\n",postAndin); while(n--) { scanf("%s",&test); Node *T2=NULL; int i=0; alloc=0; while(test[i]!=0) T2=insert(T2,test[i++]); size=0; post_order(T2); in_order(T2); postAndin[size]=0; if(strcmp(postAndin,inputResult)==0) printf("YES\n"); else printf("NO\n"); } } return 0; }