先把BST建立起,然后递归遍历判断树就好了。
#include<iostream>
#include<string>
using namespace std;
struct node{
char data;
struct node* left;
struct node* right;
};
typedef struct node tree;
tree* build(string s){
int i=0;
tree* root=NULL;
while(i<s.size()){
tree* tem= new tree;
tem->data=s[i];
tem->left=NULL;
tem->right=NULL;
if(!root){
root=tem;
}else{
tree* pre=root;
tree* now=root;
int tag=0;
while(now){
pre=now;
if(s[i]-'0'>now->data-'0'){
now=now->right;
tag=1;
}else{
now=now->left;
tag=0;
}
}
if(tag==0){
pre->left=tem;
}else{
pre->right=tem;
}
}
i++;
}
return root;
}
bool judge(tree* r1,tree* r2){
if(!r1&&!r2) return true;
if(r1->data!=r2->data) return false;
if(!r1->left&&r2->left||r1->left&&!r2->left||r1->right&&!r2->right||!r1->right&&r2->right) {
return false;
}
return judge(r1->left,r2->left)&judge(r1->right,r2->right);
}
int main(){
int n;
while(cin >> n){
if(n==0) break;
string s;
cin >> s;
while(n!=0){
string s1;
cin >> s1;
tree* h1 =build(s);
tree* h2 =build(s1);
if(judge(h1,h2)){
cout <<"YES" <<'\n';
}else{
cout <<"NO" <<'\n';
}
n--;
}
}
return 0;
}
结果:
标签:right,r1,r2,tree,C++,二叉,KY124,now,left From: https://www.cnblogs.com/llllmz/p/17985868