思路:首先我们要明确二叉树遍历的三种方法:
1.先序遍历(PreOrdee):根,先序遍历左子树,先序遍历右子树
2.中序遍历(InOrder):中序遍历左子树,根,中序遍历右子树
3.后序遍历(PostOrder):后序遍历左子树,后序遍历右子树,根
我们知道由中序遍历+先序/后序遍历就可以得到唯一的二叉树,而由先序+后序得到的二叉树不唯一。
由先序或后序我们可以得到当前树的根节点,然后有中序遍历确定左子树和右子树的范围及元素个数,然后递归这个过程就可以把该二叉树建造出来。
二叉树的层次遍历,就是按照从上到下,从左到右的遍历所有元素。我们可以发现这很像搜索中的广搜,我们使用一个队列就可以完成。其实这个就是树的广度优先遍历。
数组写法:
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 35;
int n, in_order[MAXN], post_order[MAXN];
vector<int> ans;
struct Node
{
int v;
int left, right;
}tree[MAXN];
int Root;
int bulid(int L1, int R1, int L2, int R2)
{
if (L1 > R1) return -1;
int root = post_order[R2];
int p = L1;
while (in_order[p] != root) p++;
int cnt = p - L1;
tree[root].left = bulid(L1, p - 1, L2, L2 + cnt - 1);
tree[root].right = bulid(p + 1, R1, L2 + cnt, R2 - 1);
return root;
}
void bfs()
{
queue<int> Q;
Q.push(Root);
while (!Q.empty())
{
int u = Q.front(); Q.pop();
ans.push_back(u);
if (tree[u].left != -1) Q.push(tree[u].left);
if (tree[u].right != -1) Q.push(tree[u].right);
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &post_order[i]);
for (int i = 0; i < n; i++) scanf("%d", &in_order[i]);
Root = bulid(0, n - 1, 0, n - 1);
bfs();
for (int i = 0; i < ans.size(); i++)
{
if (i != 0) printf(" ");
printf("%d", ans[i]);
}
printf("\n");
return 0;
}
/*
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
*/
指针写法:
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 35;
int n, in_order[MAXN], post_order[MAXN];
vector<int> ans;
struct Node
{
int v;
Node *left, *right;
};
Node *Root;
Node* bulid(int L1, int R1, int L2, int R2)
{
if (L1 > R1) return nullptr;
Node *root = new Node;
root->v = post_order[R2];
int p = L1;
while (in_order[p] != root->v) p++;
int cnt = p - L1;
root->left = bulid(L1, p - 1, L2, L2 + cnt - 1);
root->right = bulid(p + 1, R1, L2 + cnt, R2 - 1);
return root;
}
void bfs()
{
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", &post_order[i]);
for (int i = 0; i < n; i++) scanf("%d", &in_order[i]);
Root = bulid(0, n - 1, 0, n - 1);
bfs();
for (int i = 0; i < ans.size(); i++)
{
if (i != 0) printf(" ");
printf("%d", ans[i]);
}
printf("\n");
return 0;
}
/*
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
*/