题目1009:二叉搜索树
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:4084
解决:1828
-
题目描述:
-
判断两序列是否为同一二叉搜索树序列
-
输入:
-
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
-
输出:
-
如果序列相同则输出YES,否则输出NO
-
样例输入:
-
2 567432 543267 576342 0
-
样例输出:
-
YES NO
这题的思路就是先对给出的序列构造排序二叉树,由于这些给出的序列排序二叉树中序遍历的结果一致,并且可以证明,如果两个序列的的前序遍历和中序遍历一致,那他们必定是同一个序列。所以,在此题中直接判断构造好的序列的前序是否一致就OK喽。
#include<iostream> #include<string> #include<algorithm> #include<cstdio> #include<cstring> #include<cmath> using namespace std; typedef struct node { int data; struct node *l,*r; }binNode,binTree; void Insert(binTree* t,int x) { binTree f,p; p=*t; while(p!=NULL) { f=p; p=(x<p->data)?p->l:p->r; } p=(binTree)malloc(sizeof(binNode)); p->data=x; p->l=NULL;p->r=NULL; if(*t==NULL) *t=p; else if(x<f->data) f->l=p; else f->r=p; } binTree creat(string s;) { binTree t=NULL; for(i=0;i<s.size();i++) Insert(&t,s[i]-'0'); return t; } void inorder(binTree t) { if(t!=NULL) { inorder(t->l); cout<<t->data; inorder(t->r); } } int main() { string s; int n; binTree t; while(cin>>n && n) { cin>>s; t=creat(s); inorder(t); } return 0; }