题目
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
思路
这题的思路就是利用后序和前序得到二叉树,然后在进行层序遍历
代码呈现
#include<iostream>
#include<queue>
using namespace std;
const int N = 31;
typedef struct Tree{
int data;
struct Tree* left;
struct Tree* right;
}BinTree;
typedef BinTree* BinT;
int post_Tree[N];//后序输入
int mid_Tree[N];//中序输入
BinTree* create(int post_l, int post_r, int mid_l, int mid_r){
if(post_l > post_r) return NULL;
BinT root = new BinTree;
root->data = post_Tree[post_r];
int index;
//找到与根节点相同的点
for (index = 0; index < mid_r; index ++){
if (post_Tree[post_r] == mid_Tree[index]){
break;
}
}
// 不理解的后面有知识点的补充
root->left = create(post_l, post_l + index - mid_l - 1, mid_l, index - 1);
root->right = create(post_l + index - mid_l, post_r - 1, index + 1, mid_r);
return root;
}
//层序遍历 不理解的后面有知识点的补充
void LevelOrder(BinT BT){
queue<BinT>q;
int flog = 1;
if(BT){
BinT temp;
q.push(BT);
while(!q.empty()){
temp = q.front();
q.pop();
if (flog) cout << temp->data, flog = 0;
else cout << " " << temp->data;
if (temp->left != NULL) q.push(temp->left);
if (temp->right != NULL) q.push(temp->right);
}
}
}
int main(){
int n;
cin >> n;
for (int i = 0; i < n; i ++) cin >> post_Tree[i];
for (int i = 0; i < n; i ++) cin >> mid_Tree[i];
BinT root = create(0, n - 1, 0, n - 1);
LevelOrder(root);
}
知识点补充
1、层序遍历
先用一个队列来存结点 输出元素
然后看这个结点有没有左右结点
都有的话先存左节点,因为队列先进先出
void LevelOrder(BinT BT){
queue<BinT>q;//定义一个结点类型的队列
int flog = 1;
if(BT){
BinT temp;//定义一个结点用来存队列中的第一个结点
q.push(BT);//放入根节点 这个时候队列一定不会是空的
while(!q.empty()){
temp = q.front();//把对立的第一个元素,给temp;
q.pop();//删除队列第一个元素
//输出这个树结点的值
if (flog) cout << temp->data, flog = 0;
else cout << " " << temp->data;
//将这个结点的左右还在放进队列(如过有的话)
if (temp->left != NULL) q.push(temp->left);
if (temp->right != NULL) q.push(temp->right);
}
}
}
2、通过后序和中序得到而二叉树
首先后序的根节点是在后面的,这个时候我们在中序里面找到与之匹配的元素 这个位置为index
在index的左边便是左子树,在它的右边便是右子树
然后后序遍历的规则是左孩子 右孩子 根节点
我们可以通过index减去中序遍历的第一个的位置,得到当前这个根节点一共多少个左子树元素
后面的就是右子树的元素个数
BinTree* create(int post_l, int post_r, int mid_l, int mid_r){
if(post_l > post_r) return NULL;
BinT root = new BinTree;//分配一个空间
root->data = post_Tree[post_r];//根结点
int index;
//找到与根节点相同的点
for (index = 0; index < mid_r; index ++){
if (post_Tree[post_r] == mid_Tree[index]){
break;
}
}
// 左子树的所有元素个数有index - mid_l个,然后数组是0开始的 所以地index - mid_l个下标为 post_l + index - mid_l - 1;
//可以得到在后序遍历中,根节点的左子树的在post_l 到post_l + index - mid_l - 1 而在中序遍历中,它的左边就是左子树所以是mid_l到index - 1
root->left = create(post_l, post_l + index - mid_l - 1, mid_l, index - 1);
//那么post_l + index - mid_l 到 post_r - 1 为右子树 因为最后一个为根节点
//中序中index + 1, mid_r为右子树
root->right = create(post_l + index - mid_l, post_r - 1, index + 1, mid_r);
return root;
}