#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;
}
pta 7-4 树的遍历
最新推荐文章于 2025-03-19 21:31:57 发布