浙大机试OJ——二叉搜索树

|题目描述:

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

|输入描述:

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

输出描述:

如果序列相同则输出YES,否则输出NO

示例1

输入

2
567432
543267
576342
0

输出

YES
NO

|解题思路:

前序遍历和中序遍历可以唯一确定一棵二叉树,对于二叉排序树,相同元素的二叉排序树中序遍历一定相同,而不同元素二叉排序树使用前序遍历就可以发现不相同,所以只需要前序遍历两个二叉树,比较两者是否相同就可以判断。

|具体代码:

#include<bits/stdc++.h>
using namespace std;

struct node{
    int x;
    node * lchild;
    node* rchild;
}Tree[1000];
 
int size = 0;
 
node * create(){
    Tree[size].lchild = Tree[size].rchild = NULL;
    return &Tree[size++];
}
 
node * build(node* tree, int x){
    if(tree == NULL){
        tree = create();
        tree->x = x;
        return tree;
    }else if(x > tree->x){
        tree->rchild = build(tree->rchild,x);
    }else if(x < tree->x){
        tree->lchild = build(tree->lchild,x);
    }
    return tree;
}
 
int count=0;
void preorder(node* tree, int a[]){
    if(tree == NULL) return;
    a[count++] = tree->x;
    a[count] = 0;
    before(tree->lchild,a);
    before(tree->rchild,a);
}
 
int main(){
    int n;
    while(cin >> n && n!=0){
        string s;
        cin >> s;
        node* tree = NULL;
        for(int i=0; i<s.size(); i++){
            tree=build(tree,s[i]-'0');
        }
        for(int i=0; i<n; i++){
            string s1;
            node* tree1 = NULL;
            cin >> s1;
            for(int i=0; i<s1.size(); i++){
                tree1=build(tree1,s1[i]-'0');
            }
            int a[50],b[50];
            preorder(tree,a);
            count=0;
            preorder(tree1,b);
            count=0;
            int flag=1;
            for(int i=0; i<s.size(); i++){
                if(a[i] != b[i])
                    flag = 0;
            }
            if(flag) cout << "YES" << endl;
            else cout << "NO" << endl;
        }
    }
    return 0;
}

关于二叉树的问题还是挺容易出现的,对这个知识点掌握得还不好,继续加油吧!ヾ(◍°∇°◍)ノ゙

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值