二叉树的遍历方式分为:先序遍历、中序遍历、后序遍历、层次遍历
其中,中序序列与先序序列、后序序列、层次序列,两两组合均能确立一个唯一的二叉树
1、中序序列和先序序列
事实上,如果递归过程中当前先序序列的区间为[preL, preR], 中序序列的区间为[inL, inR], 那么左子树的节点个数为:numLeft = k - inL。这样左子树的先序序列区间就是[preL+1, preL +numLeft],左子树的中序序列区间是[inL, k-1],右子树的先序序列区间就是[preL + numLeft+1, preR], 右子树的中序序列是[k + 1, inR]
注:递归边界:先序序列的长度小于0,即 preL > preR
#include <cstdio>
const int maxn = 50;
int n; //n个结点
stuct node{
int data;
node* lchild;
node* rchild;
};
int pre[maxn], post[maxn], in[maxn];
node* create(int preL, int preR, int inL, int inR){
if(preL > preR){
return NULL;
}
node* root = new node;
root->data = pre[preL];
int k;
for(k = inL; k <= inR; k++){
if(in[k] == pre[preL]){
break;
}
}
int numLeft = k - inL;
//左子树[preL+1, preL+numLeft, inL, k-1];
root->lchild = create(preL+1, preL+numLeft, inL, k-1);
root->rchild = create(preL+numLeft+1, preR, k+1, inR);
return root;
}
int main(void){
scanf("%d", &n);
//init
for(int i = 0; i < n; i++){
scanf("%d", &pre[i]);
}
for(int i = 0; i < n; i++){
scanf("%d", &in[i]);
}
node* root = create(0, n-1, 0, n-1);
return 0;
}
2、中序序列和后序序列
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 50;
struct node{
int data;
node* lchild;
node* rchild;
};
int pre[maxn], post[maxn], in[maxn];
int n; //结点个数
node* create(int postL, int postR, int inL, int inR){
if(postL > postR){
return NULL;
}
node* root = new node;
root->data = post[postR];
int k;
for(k = inL; k <= inR; k++){
if(in[k] == post[postR]){
break;
}
}
int numLeft = k - inL;
root->lchild = create(postL, postL + numLeft -1, inL, k - 1);
root->rchild = create(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
int num = 0; //已输出的结点个数
void bfs(node* root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node* now = q.front();
q.pop();
printf("%d", now->data);
num++;
if(num < n)
printf(" ");
if(now->lchild != NULL)
q.push(now->lchild);
if(now->rchild != NULL)
q.push(now->rchild);
}
}
int main(void){
scanf("%d", &n);
//init
for(int i = 0; i < n; i++){
scanf("%d", &post[i]);
}
for(int i = 0; i < n; i++){
scanf("%d", &in[i]);
}
node* root = create(0, n-1, 0, n-1);
bfs(root);
return 0;
}
3、已知层次序列和中序序列,求先序序列
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
//因为层序是先输出根节点的,所以可以递归查找
string s1,s2; //s1:中序序列 s2:层次序列
void find(int inL, int inR, int levelL, int levelR)
{
int i, j;
for(i = levelL; i <= levelR; i++)//找层次遍历中优先输出根节点的位置
{
int f = 0; //是否存在
for(j = inL; j <= inR; j++)
{
if(s2[i] == s1[j])//输出根节点
{
cout << s1[j];
f = 1;
break;
}
}
if(f)
break;
}
if(j > inL)
find(inL, j - 1, 0, levelR);//遍历左子树
if(j < inR)
find(j + 1, inR, 0, levelR);//遍历右子树 i
}
int main()
{
cin >> s1 >> s2;
//中序、层次i
find(0, s1.length()-1, 0, s2.length());
return 0;
}