二叉搜索樹
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8045 Accepted Submission(s): 3574
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
思路:
建樹,遍歷判斷遍歷序列是否相同
代碼如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<stack>
using namespace std;
struct node{
struct node *lc,*rc;
int data;
};
node *Insert(node *t,int e){
node *q=new node;
q->data=e;
q->lc=NULL;
q->rc=NULL;
node *p=t;
if(t==NULL){
t=q;
return t;
}
while(p!=NULL){
if(p->data>e){//向左
if(p->lc)p=p->lc;
else {
p->lc=q;
break;
}
}
else{//向右
if(p->rc)p=p->rc;
else{
p->rc=q;
break;
}
}
}
return t;
}
bool judge(node *t,node *s){
if(t&&s){
return t->data==s->data&&judge(t->lc,s->lc)&&judge(t->rc,s->rc);
}
if(t==NULL&&s==NULL){
return true;
}
else{
return false;
}
}
void print(node *T){
if(T){
printf("%d",T->data);
print(T->lc);
print(T->rc);
}
}
int main(){
int n;
char ch;
while(scanf("%d",&n)&&n){
getchar();
node *t=NULL;
while((ch=getchar())&&ch!='\n'){
t=Insert(t,ch-'0');
}
for(int i=1;i<=n;i++){
node *s=NULL;
while((ch=getchar())&&ch!='\n'){
s=Insert(s,ch-'0');
}
if(judge(t,s)){
printf("YES\n");
}
else printf("NO\n");
}
}
}