SDUT3374数据结构实验之查找一:二叉排序树

判断是否为同一棵二叉排序树

解决这个问题需要两步:
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;
}

猜你喜欢

转载自blog.csdn.net/Jinx_vt_Lin/article/details/85078444