pta--玩转二叉树

#include <bits/stdc++.h>
using namespace std;
typedef struct node *tree;
int in[1000], pre[1000];
struct node
{
    int data;
    tree left, right;
};

tree build(int in[], int pre[], int n)
{
    tree t;
    if (!n)
        return NULL;
    t = (tree)malloc(sizeof(struct node));
    t->data = pre[0];
    t->left = t->right = NULL;
    int i;
    for (i = 0; i < n; i++)
    {
        if (in[i] == pre[0])
            break;
    }
    t->left = build(in, pre + 1, i);
    t->right = build(in + i + 1, pre + i + 1, n - i - 1);
    return t;
}

tree change(tree t)
{
    tree m;
    if (t)
    {
        if (t->left != NULL || t->right != NULL)
        {
            m = t->left;
            t->left = t->right;
            t->right = m;
        }
        change(t->left);
        change(t->right);
    }
    return t;
}

void cengci(tree t, int n)
{
    tree q[100], p;
    int ll = 0, rr = 0, len = 0;
    if (t)
    {
        q[rr++] = t;
        while (ll != rr)
        {
            p = q[ll++];
            printf("%d", p->data);
            len++;
            if (len != n)
            {
                printf(" ");
            }
            else
                cout << endl;
            if (p->left != NULL)
                
            q[rr++] = p->left;
            if (p->right != NULL)
            {
                q[rr++] = p->right;
            }
        }
    }
}
int main()
{
    tree t;
    int i, n;
    cin >> n;
    for (i = 0; i < n; i++)
    {
        cin >> in[i];
    }
    for (i = 0; i < n; i++)
    {
        cin >> pre[i];
    }
    t = build(in, pre, n);
    t = change(t);
    cengci(t, n);
    return 0;
}

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值