1.已知后、中序序列,输出层序、前序序列
//已知中序序列与后序序列求二叉树
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
const int N = 40;
int n;
int postorder[N],inorder[N];
queue<int> q;
unordered_map<int,int> l,r,pos;//lr存储每一个非叶子结点的左右节点,pos存储根节点的位置
//输入中序序列、后序序列区间,通过递归方式构建二叉树,返回父节点
int build (int il,int ir,int pl,int pr) {
int root = postorder[pr];
int k = pos[root];
if (k>il)
/*
易知中序序列区间为(il,k-1)
后序序列的个数应=中序序列个数相同=k-1-il
后序序列起点为pl,终点为pl+(k-1-il)
*/
l[root] = build (il,k-1,pl,pl + (k-1-il)) ;
if (k<ir)
/*
由左子树起点知道右子树起点pl+(k-1-il)+1
去掉后序序列最后一个根节点 pr-1
*/
r[root] = build (k+1,ir,pl + (k-1-il) + 1 , pr - 1 );
return root;
}
void levelorder (int root) {
q.push(root);
while (!q.empty()) {
cout << q.front() << " ";
int t = q.front();
if (l.count(t))
q.push(l[t]);
if (r.count(t))
q.push(r[t]);
q.pop();
}
}
void preorder (int root) {
cout << root << ' ';
int t = root;
if (l.count(t))
preorder(l[t]);
if (r.count(t))
preorder(r[t]);
}
int main () {
cin >> n;
for (int i = 0 ; i < n ; i ++ )
cin >> postorder[i];
for (int i = 0 ; i < n ; i ++ ){
cin >> inorder[i];
pos[inorder[i]] = i;
}
int root = build (0,n-1,0,n-1);
//level order traversal sequence
levelorder(root);
cout << endl;
//preorder traversal sequence
preorder(root);
cout << endl;
system ("pause");
return 0;
}
2.已知前、中序序列,输出层序、后序序列
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
const int N = 40;
int n;
int preorder[N],inorder[N];
queue<int> level_q,post_q;
unordered_map<int,int> l,r,pos;
int build (int pl,int pr,int il,int ir) {
int root = preorder[pl];
int k = pos[root];
if (k>il)
l[root] = build (pl+1,pl + k - il,il,k-1) ;
if (k<ir)
r[root] = build (pl+k-il+1,pr,k+1,ir);
return root;
}
void levelorder (int root) {
level_q.push(root);
while (!level_q.empty()) {
cout << level_q.front() << " ";
int t = level_q.front();
if (l.count(t))
level_q.push(l[t]);
if (r.count(t))
level_q.push(r[t]);
level_q.pop();
}
}
void postorder (int root) {
int t = root;
if (l.count(t))
postorder(l[t]);
if (r.count(t))
postorder(r[t]);
post_q.push(root);
}
int main () {
cin >> n;
for (int i = 0 ; i < n ; i ++ )
cin >> preorder[i];
for (int i = 0 ; i < n ; i ++ ){
cin >> inorder[i];
pos[inorder[i]] = i;
}
int root = build (0,n-1,0,n-1) ;
levelorder(root);
cout << endl;
postorder(root);
while (!post_q.empty()) {
cout << post_q.front() << ' ';
post_q.pop();
}
cout << endl;
system ("pause");
return 0;
}