二叉搜索树 hdu3791

本文介绍了一种使用C++实现的二叉搜索树构建方法,并通过对比两个字符串构建的二叉搜索树来判断它们是否相同。文章详细展示了如何递归地构建二叉搜索树,以及如何遍历树进行比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉搜索树,建立在二叉树之上:

对于每一棵子树

左儿子的值小于根节点,右儿子的值大于根节点

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn = 50000;
char a[maxn];
char b[maxn];
int tree1[maxn];
int tree2[maxn];
void insert(char ch, int *tree)//建立二叉搜索树
{
    int rt = 1;
    int value = ch - '0';//节点的键值
    while(tree[rt] != -1)//递归建树
    {
        if(tree[rt] < value)
            rt = 2 * rt + 1;
        else
            rt = 2 * rt;
    }
    tree[rt] = value;
}
void build(char *s , int *tree)
{
    tree[1] = s[0] - '0';//将字符串第一个值加入树,作为根节点
    for(int i = 1;s[i]; i ++)//循环字符串,将每个值加入树中
        insert(s[i],tree);
}
int main(void)
{
    int n;
    while(cin>>n)
    {
        if(n == 0)
            return 0;
        cin>>a;
        memset(tree1,-1,sizeof(tree1));
        build(a,tree1);
        while(n --)
        {
            cin>>b;
            memset(tree2,-1,sizeof(tree2));
            int flag = 0;
            build(b,tree2);
            for(int i = 0 ; i < 50000 ; i ++)
            {
                if(tree1[i] != tree2[i])
                {
                    flag = 1;
                    break;
                }
            }
            if(flag)
                cout<<"NO"<<endl;
            else
                cout<<"YES"<<endl;
        }
    }
}
//可以输出tree1的值,看看树的结构

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值