hdu 3791 二叉查找树,BST

本文介绍了一种基于关键字树的数据结构实现,用于判断两棵树是否相同。通过前序遍历和中序遍历的方式,该算法能够有效地对比两棵关键字树是否结构一致。使用C++实现,并提供了一个具体的示例程序。
796093asia2562219FAccepted524 KB15 msG++1525 B2012-11-04 12:37:34

关键字树~ 简单题。。

前序 中序 判同。

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
#define MAXN 11111
struct Node
{
char data;
Node* left;
Node* right;
};
class BTree
{
public:
Node *root;
void init(char *ch)
{
Node* temp[100];
int front=0;
Node *ptr,*now,*temp1;

while(ch[front]!='\0')
{
    ptr=new Node;
    ptr->data=ch[front];
    ptr->left=NULL;
    ptr->right=NULL;
    temp[++front]=ptr;
    if(1==front)
    {
        root=ptr;
    }
    else
    {
        now=root;
        while(now!=NULL)
        {
            temp1=now;
            if(ptr->data>now->data)
            now=now->right;
            else now=now->left;
        }
        if(ptr->data>temp1->data)
            temp1->right=ptr;
        else temp1->left=ptr;
    }

}
;
}
void first(Node *now,string &s)
{
if(now==NULL)return;
s+=now->data;
first(now->left,s);
first(now->right,s);
}
void mid(Node *now,string &s)
{
if(now==NULL)return;
mid(now->left,s);
s+=now->data;
mid(now->right,s);
}
bool operator == (BTree o)
    {
         string s1,s2;
         first(root,s1);
         first(o.root,s2);
         if(s1!=s2)return 0;
         mid(root,s1);
         mid(o.root,s2);
         if(s1!=s2)return 0;
         return 1;
    }
}temp,cmp;

int main()
{
int n;
char ch[12];
while(scanf("%d",&n),n)
{
    scanf("%s",ch);
    temp.init(ch);
    for(int i=0;i<n;i++)
    {
        scanf("%s",ch);
        cmp.init(ch);
        if(cmp==temp)
        printf("YES\n");
        else printf("NO\n");
    }
}


return 0;
}

时间压力好大

转载于:https://www.cnblogs.com/TO-Asia/archive/2012/11/04/2753424.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值