两棵树是否相同

核心是任意两种包括中序遍历的遍历结果相同,则树相同

理解了一点指针的用法

#include<iostream>
#include<string.h>
using namespace std;

struct Node{
    Node* lch;
    Node* rch;
    int num;
}tree[110];

int k,l;
Node* create()
{
    tree[l].lch = tree[l].rch = NULL;
    return &tree[l++];
}

Node* insert(int c,Node *t){
    if (t == NULL)
    {
        t = create();
        t->num = c;
        return t;
    }
    else if (c >= t->num)
    {
        t->rch = insert(c, t->rch);
    }
    else if (c < t->num)
    {
        t->lch = insert(c, t->lch);
    }
    return  t;
}

char str1[25], str2[25];//字符串前序遍历和中序遍历字符串的链接
int size1, size2;
char *str;
int *size;
//中序遍历
void midOrder(Node *t)
{
    if (t->lch != NULL)
        midOrder(t->lch);
    str[(*size)++] = t->num + '0';
    if (t->rch != NULL)
        midOrder(t->rch);
}
//后序遍历
void postOrder(Node* t)
{
    if (t->lch != NULL)
        postOrder(t->lch);
    if (t->rch != NULL)
        postOrder(t->rch);
    str[(*size)++] = t->num+'0';
}
int main(){
    int n;
    char tmp[12];
    while (cin >> n)
    {
        if (n == 0)
            return 0;
        cin >> tmp;
        Node*T = NULL;
        l = 0;
        for (int i = 0; tmp[i]!=0; i++)
        {
            T = insert(tmp[i]-'0', T);
        }
        size1 = 0;
        str = str1;
        size = &size1;
        midOrder(T);
        postOrder(T);
        str1[size1] = '\0';
        while (n--)
        {
            cin >> tmp;
            Node *T1 = NULL;
            for (int i = 0;tmp[i]!=0; i++)
                T1 = insert(tmp[i] - '0', T1);
            size2 = 0;
            size = &size2;
            str = str2;
            midOrder(T1);
            postOrder(T1);
            str2[size2] = '\0';
            if (strcmp(str1, str2) == 0)
                puts("yes");
            else puts("no");
        }
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值