SDUT3374資料結構實驗之查詢一:二叉排序樹
阿新 • • 發佈:2018-12-19
判斷是否為同一棵二叉排序樹
解決這個問題需要兩步:
1.建立二叉排序樹
2.判斷兩棵樹是否相同
詳情看程式碼和註釋,懶人程式碼
#include <iostream>
#include <cstring>
using namespace std;
typedef struct note{
int data;
struct note *l,*r;
}tree;
void creat(tree *&root, int x){//c++中想要對樹進行操作,引用時前面要加&
if(root==NULL){//若為空節點,則建立結點,給結點賦值,並使他的左右兒子為NULL
root = new tree;
root->data = x;
root->l = NULL;
root->r = NULL;
return ;
}
else{//如果非NULL 則判斷新加入的值x 與 當前root中的data值的大小關係
if(x>root->data)
creat(root->r,x);
else
creat(root->l,x);
}
}
int z;
void qianxu(tree *root,char a[]){//通過前序遍歷將data值儲存到陣列中,再通過strcmp來判斷陣列是否相等
if(root){
a[z++] = root->data;
qianxu(root->l,a);
qianxu(root->r,a);
}
}
int main()
{
int n,l;
while(cin>>n){
if(!n)
break;
cin>>l;
tree * root = NULL;
for(int i=0; i<n; i++){
int x;
cin>>x;
creat(root,x);
}
char a[11];
z = 0;
qianxu(root,a);
a[n] = '\0';
char b[11];
for(int i=0; i<l; i++){
tree *root2 = NULL;
for(int j=0; j<n; j++){
int x;
cin>>x;
creat(root2,x);
}
z = 0;
qianxu(root2,b);
b[n]='\0';//不要忘記封口哦
if(strcmp(a,b)==0)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
}
return 0;
}