hdu3791二叉搜索树

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3791

题意:给定一个n(多组,n为0时结束),给一个串和n个串,分别判断n个串按序列构建的二叉搜索树和第一给串相同。分别转换成先序判断。

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int v;
    node *left,*right;
}*root;
node* build(node *root,int v)
{
    if(root==NULL)
    {
        root=new node();
        root->v=v;
        root->left=root->right=NULL;
    }
    else if(v<=root->v)root->left=build(root->left,v);
    else root->right=build(root->right,v);
    return root;
}

string ans1,ans2,s; 
void dfs(node *root)
{
    ans1+=to_string(root->v);
    if(root->left!=NULL)dfs(root->left);
    if(root->right!=NULL)dfs(root->right); 
}
int main()
{
    int n;
    while(cin>>n&&n)
    {
        ans1="";
        root=NULL;
        cin>>s; 
        for(int i=0;s[i];i++)root=build(root,s[i]-'0');
        dfs(root);
        ans2=ans1;
            
        while(n--)
        {    
            ans1="";
            root=NULL; 
            cin>>s; 
            for(int i=0;s[i];i++)root=build(root,s[i]-'0');
            dfs(root);
            
            if(ans1==ans2)cout<<"YES"<<endl;
            else cout<<"NO"<<endl;
        } 
    }
    return 0;
} 
posted @ 2019-12-12 14:48  myrtle  阅读(117)  评论(0编辑  收藏  举报