ACM 数据结构-二叉树 HDU 3791二叉搜索树

本文介绍了一个通过比较不同序列来判断它们是否能构成相同的二叉搜索树的问题。输入包括一组序列,需判断这些序列是否能形成相同的二叉搜索树结构。文章提供了完整的C++实现代码,展示了如何构造二叉搜索树并进行序列比对。
<div class="panel_title" align="left">Problem Description</div><div class="panel_content">判断两序列是否为同一二叉搜索树序列</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Input</div><div class="panel_content">开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Output</div><div class="panel_content">如果序列相同则输出YES,否则输出NO
</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Sample Input</div><div class="panel_content"><pre><div style="FONT-FAMILY: Courier New,Courier,monospace">2
567432
543267
576342
0</div>
 

Sample Output
  
YES NO
 

Source
 

 
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stdlib.h>
using namespace std;

int a[30],b[30],cnt = 0;

typedef struct tree
{
    tree *l,*r;
    int num;
} tree;
tree *root;
tree *creat(int x)
{
    tree *t = (tree*)malloc(sizeof(tree));
    t->l = 0;
    t->r = 0;
    t->num = x;
    return t;
}

tree *inster(tree *s,int x)
{
    tree *t;
    if(s == NULL)
    {
        t = creat(x);
        s = t;
    }
    else
    {
        if(x <= s->num)
            s->l = inster(s->l,x);
        else
            s->r = inster(s->r,x);
    }
    return s;
}

void libian(tree *root)
{
    if(root!=NULL)
    {
        b[cnt++] = root->num;
        libian(root->l);
        libian(root->r);
    }
}

int main()
{
    int n;
    while(cin >> n,n)
    {
        cnt = 0;
        root = NULL;
        int tem;
        char str[30];
        cin >> str;
        int len = strlen(str),i;
        for(i = 0; i<len; i++)
        {
            tem = str[i] - '0';
            root = inster(root,tem);
        }
        libian(root);
        for(i = 0; i<len; i++)
            a[i] = b[i];
        while(n--)
        {
            cnt = 0;
            cin >> str;
            root = NULL;
            for(i = 0; i<len; i++)
            {
                tem = str[i] - '0';
                root = inster(root,tem);
            }
            libian(root);
            for(i = 0; i<len; i++)
                if(a[i]!=b[i])
                {
                    cout << "NO" << endl;
                    break;
                }
            if(i>=len)
                cout << "YES" << endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值