二叉搜索树

题目描述
Time Limit: 1000 ms
Memory Limit: 256 mb
判断两序列是否为同一二叉搜索树序列

输入输出格式
输入描述:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出描述:
如果序列相同则输出YES,否则输出NO
输入输出样例
输入样例#:
复制
2
567432
543267
576342
0
输出样例#:
复制
YES
NO
题目来源
浙江大学机试题

#include<iostream>
#include<cstring>
using namespace std;
 char a[15],b[15];
 int o = 0,m = 0;
struct tree{
    char num;
    struct tree *lchild,*rchild;
};
  struct tree *create(struct tree *&p,char x){
    if(p == NULL){
        p = (tree*)malloc(sizeof(tree));
        p ->num = x;
        p ->lchild = NULL;
        p ->rchild  = NULL;
    }
    else if(x < p ->num){
        create(p ->lchild,x);
    }
    else if(x > p->num){
        create(p ->rchild,x);
    }
    return p;
  }
  void inorder1(struct tree *p,int i){
      if(p != NULL){
          inorder1(p ->lchild,i);
          
          a[o++] = p ->num;
          inorder1(p ->rchild,i);
      }
  }
 void inorder2(struct tree *p,int i){
      if(p != NULL){
          inorder2(p ->lchild,i);
    
          b[m++] = p ->num;
          inorder2(p ->rchild,i);
      }
  }

int main(){
struct tree *p = NULL;
int n;
cin>>n;
while(n--){
    o = 0;  //数组下标归零
    m = 0;
    for(int i = 0;i < 15;i++){   //数组清空
        a[i] = '\0';
        b[i] = '\0';
    }
   
 struct tree *p = NULL;  //比较两个数,就要建两个根节点
 struct tree *q = NULL;
 cin>>a;         //把序列输入数组
int len1  = strlen(a);
 cin>>b;
int len2  = strlen(b);
if(len1 != len2)    //长度不等直接NO
{
    cout<<"NO"<<endl;
    
    continue;
}
for(int i = 0;i < len1;i++){
   p = create(p,a[i]);    //用a得序列建树
}
for(int i = 0;i < len2;i++){//同理
   q = create(q,b[i]);
}
inorder1(p,0);  //如果排序树相同,中序遍历一定相同,并覆盖a,b得记录
inorder2(q,0);
int f = 0;
for(int l = 0,k = 0; l < len1,k < len2;l++,k++ ){  
    if(a[l] != b[k]){   //比较中序序列
        f = 1;
        break;
    }
}

if(f == 0) cout<<"YES"<<endl;
else if(f == 1) cout<<"NO"<<endl;
}


    return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值