pta 7-4 树的遍历

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

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

void cengci(tree t, int n)
{
    tree q[100], p;
    int ll = 0;
    int rr = 0;
    int len = 0;
    if (n)
    {
        q[rr++] = t;
        while (ll != rr)
        {
            p = q[ll++];
            cout << p->data;
            len++;
            if (len != n)
                cout << " ";
            else
            {
                cout << endl;
            }
            if (p->left != NULL)
            {
                q[rr++] = p->left;
            }
            if (p->right != NULL)
            {
                q[rr++] = p->right;
            }
        }
    }
}

int main()
{
    int n;
    cin >> n;
    int in[31], pos[31];
    for (int i = 0; i < n; i++)
    {
        cin >> pos[i];
    }
    for (int i = 0; i < n; i++)
    {
        cin >> in[i];
    }
    tree t;
    t = build(in, pos, n);
    cengci(t, n);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值