思路:树的遍历互求,中序前序建树。对于交换非叶子节点的左右孩子,可以通过层序遍历的时候让右子树先入队,左子树后入队。也可以通过遍历交换之后,层序遍历即可。
我采取的链表方式建树,也可以用数组模拟。
右子树先入队:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 35;
int n, in_order[MAXN], pre_order[MAXN];
vector<int> ans;
struct Node
{
int v;
Node *left, *right;
};
Node *Root;
Node* build(int L1, int R1, int L2, int R2)
{
if (L1 > R1) return nullptr;
Node *root = new Node;
root->v = pre_order[L2];
int p = L1;
while (in_order[p] != root->v) p++;
int cnt = p - L1;
root->left = build(L1, p - 1, L2 + 1, L2 + cnt);
root->right = build(p + 1, R1, L2 + cnt + 1, R2);
return root;
}
void bfs(Node *root)
{
queue<Node*> Q;
Q.push(Root);
while (!Q.empty())
{
Node *u = Q.front(); Q.pop();
ans.push_back(u->v);
if (u->right != nullptr) Q.push(u->right);
if (u->left != nullptr) Q.push(u->left);
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &in_order[i]);
for (int i = 0; i < n; i++) scanf("%d", &pre_order[i]);
Root = build(0, n - 1, 0, n - 1);
bfs(Root);
for (int i = 0; i < n; i++)
{
printf("%d", ans[i]);
if (i != n - 1) printf(" ");
}
printf("\n");
return 0;
}
/*
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
*/
交换:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 35;
int n, in_order[MAXN], pre_order[MAXN];
vector<int> ans;
struct Node
{
int v;
Node *left, *right;
};
Node *Root;
Node* build(int L1, int R1, int L2, int R2)
{
if (L1 > R1) return nullptr;
Node *root = new Node;
root->v = pre_order[L2];
int p = L1;
while (in_order[p] != root->v) p++;
int cnt = p - L1;
root->left = build(L1, p - 1, L2 + 1, L2 + cnt);
root->right = build(p + 1, R1, L2 + cnt + 1, R2);
return root;
}
void Reverse(Node *root)
{
if (root == nullptr) return ;
Node *t= root->left;
root->left = root->right;
root->right = t;
Reverse(root->left);
Reverse(root->right);
}
void bfs(Node *root)
{
queue<Node*> Q;
Q.push(Root);
while (!Q.empty())
{
Node *u = Q.front(); Q.pop();
ans.push_back(u->v);
if (u->left != nullptr) Q.push(u->left);
if (u->right != nullptr) Q.push(u->right);
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &in_order[i]);
for (int i = 0; i < n; i++) scanf("%d", &pre_order[i]);
Root = build(0, n - 1, 0, n - 1);
Reverse(Root);
bfs(Root);
for (int i = 0; i < n; i++)
{
printf("%d", ans[i]);
if (i != n - 1) printf(" ");
}
printf("\n");
return 0;
}
/*
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
*/