zcmu——4934: 二叉搜索树

17 篇文章 0 订阅

题目链接

【分析】

一开始不知道如何做

因为觉得一个序列不可能确定一颗唯一的树

其实二叉搜索树(或者二叉查找数、二叉排序树)是可以的

它的左孩子永远小于根

右孩子永远大于根

所以还以那一套模板

建树、建结点、插入

然后判断是否是同一个二叉搜索树可以先用前序遍历

然后看看遍历出来的顺序是否相等

就可以了

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
struct node{
    char data;
    node* lchild;
    node* rchild;
};
node* newNode(char v)
{
    node* Node=new node;
    Node->data=v;
    Node->lchild=Node->rchild=NULL;
    return Node;
}
void insert(node* &root,char x)//这里&要注意,根可能一直在变化
{
    if(root==NULL)
        {
            root=newNode(x);
            return;
        }
    if(root->data==x)
        return;
    else if(x<root->data)
        insert(root->lchild,x);
    else
        insert(root->rchild,x);
}
node* create(string data,int n)
{
    node* root=NULL;
    for(int i=0;i<n;i++)
        insert(root,data[i]);
    return root;
}
void preorder(node* root,string& str)//这里的&也要注意,可能一直在变化
{
    if(root==NULL)
        return;
    str+=root->data;
    preorder(root->lchild,str);
    preorder(root->rchild,str);
}
int main()
{
    int t;
    while(~scanf("%d",&t)&&t!=0)
    {
        string str;
        cin>>str;
        int len=str.size();
        node* root=create(str,len);
        string ret1;
        preorder(root,ret1);
        while(t--)
        {
            cin>>str;
            node* Proot=create(str,len);
            string ret2;
            preorder(Proot,ret2);
            if(ret1==ret2)
                printf("YES\n");
            else
                printf("NO\n");
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值