|題目描述:
判斷兩序列是否爲同一二叉搜索樹序列
|輸入描述:
開始一個數n,(1<=n<=20) 表示有n個需要判斷,n= 0 的時候輸入結束。 接下去一行是一個序列,序列長度小於10,包含(0~9)的數字,沒有重複數字,根據這個序列可以構造出一顆二叉搜索樹。 接下去的n行有n個序列,每個序列格式跟第一個序列一樣,請判斷這兩個序列是否能組成同一顆二叉搜索樹。
輸出描述:
如果序列相同則輸出YES,否則輸出NO
示例1
輸入
2 567432 543267 576342 0
輸出
YES NO
|解題思路:
前序遍歷和中序遍歷可以唯一確定一棵二叉樹,對於二叉排序樹,相同元素的二叉排序樹中序遍歷一定相同,而不同元素二叉排序樹使用前序遍歷就可以發現不相同,所以只需要前序遍歷兩個二叉樹,比較兩者是否相同就可以判斷。
|具體代碼:
#include<bits/stdc++.h>
using namespace std;
struct node{
int x;
node * lchild;
node* rchild;
}Tree[1000];
int size = 0;
node * create(){
Tree[size].lchild = Tree[size].rchild = NULL;
return &Tree[size++];
}
node * build(node* tree, int x){
if(tree == NULL){
tree = create();
tree->x = x;
return tree;
}else if(x > tree->x){
tree->rchild = build(tree->rchild,x);
}else if(x < tree->x){
tree->lchild = build(tree->lchild,x);
}
return tree;
}
int count=0;
void preorder(node* tree, int a[]){
if(tree == NULL) return;
a[count++] = tree->x;
a[count] = 0;
before(tree->lchild,a);
before(tree->rchild,a);
}
int main(){
int n;
while(cin >> n && n!=0){
string s;
cin >> s;
node* tree = NULL;
for(int i=0; i<s.size(); i++){
tree=build(tree,s[i]-'0');
}
for(int i=0; i<n; i++){
string s1;
node* tree1 = NULL;
cin >> s1;
for(int i=0; i<s1.size(); i++){
tree1=build(tree1,s1[i]-'0');
}
int a[50],b[50];
preorder(tree,a);
count=0;
preorder(tree1,b);
count=0;
int flag=1;
for(int i=0; i<s.size(); i++){
if(a[i] != b[i])
flag = 0;
}
if(flag) cout << "YES" << endl;
else cout << "NO" << endl;
}
}
return 0;
}
關於二叉樹的問題還是挺容易出現的,對這個知識點掌握得還不好,繼續加油吧!ヾ(◍°∇°◍)ノ゙