对指针建树的一些基本操作

题目描述

判断两序列是否为同一二叉搜索树序列

输入描述:

开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。

输出描述:

如果序列相同则输出YES,否则输出NO
#include <bits/stdc++.h>
using namespace std;
int n,cnt;
char ss1[20],ss2[20],scek1[30],scek2[30];

struct node{
    char ans;
    node *l,*r;
    node (char x):ans(x),l(NULL),r(NULL){}
};//节点
node *root;
void maketree(char v,node *rt){//建树过程

    if(v <= rt -> ans){
        if(rt -> l == NULL) rt -> l = new node(v);
        else maketree(v,rt -> l);
    }
    else {
        if(rt -> r == NULL) rt -> r = new node(v);
        else maketree(v,rt -> r);
    }
}
void pre(node *root,char s[]){//前序遍历
    s[cnt] = root -> ans;
    cnt++;
    if(root -> l != NULL)    pre(root -> l,s);
    if(root -> r != NULL)    pre(root -> r,s);
    return ;
}
void mid(node *root,char s[]){//中序遍历
    if(root -> l != NULL) mid(root -> l,s);
    s[cnt] = root -> ans;
    cnt++;
    if(root -> r != NULL) mid(root -> r,s);
    return ;
}
void bak(node *root){//后序遍历
    if(root -> l != NULL)    bak(root -> l);
    if(root -> r != NULL)    bak(root -> r);
    printf("%d ",root -> ans);
}
int main() {
    //freopen("in.txt","r",stdin);
    while(~scanf("%d",&n)){
        if(n == 0) break;
        scanf("%s",ss1);
        node *root = (node*)malloc(sizeof(node));
        root = new node(ss1[0]);
        for(int i = 1;i < strlen(ss1);i++)
        maketree(ss1[i],root);
        cnt = 0;
        pre(root,scek1);
        mid(root,scek1);
        scek1[cnt] = '';
        while(n--){
        scanf("%s",ss2);
        node *root = (node*)malloc(sizeof(node));//重新定义根之后似乎它的子树也被清洗掉了
        root = new node(ss2[0]);
        for(int i = 1;i < strlen(ss2);i++)
        maketree(ss2[i],root);
        cnt = 0;
        pre(root,scek2);
        mid(root,scek2);
        scek2[cnt] = '';
        if(strcmp(scek1,scek2) == 0) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
        }
    }
    return 0;
}

经过把两个字符串前序和中序遍历连起来的字符串对比一下,结果就出来了

原文地址:https://www.cnblogs.com/shimu/p/8540136.html