由后序遍历和中序遍历输出层序遍历C++,递归
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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>
#define max 31
using namespace std;
typedef struct leaf { //二叉树的节点类型
int data;
struct leaf* lchild, * rchild;
}leaf;
static int stati; //用来找到每回插入的节点数据
leaf* create(int* a, int* b,int start,int end) {//创建二叉树,右子树取值区间是从b[start]~b[end]
//每回都要判断是否符合,不符合就返回NULL
if (start <= end && stati > 0) {
//新建节点赋值
leaf* root = new leaf;
int i;
root->data = a[stati];
//在后序顺序中找到根的位置
for (i = start; i <= end; i++)
if (b[i] == root->data)
break;
stati--; //每回减1是找到每个给节点位置
//再次划分左右子树区间
root->rchild = create(a, b, i + 1, end);
root->lchild = create(a, b, start, i - 1);
return root;
}
else
return NULL;
}
int main() {
int n;
cin >> n;
int i;
int hou[max] = { 0 }, zhong[max] = { 0 } ;//后序,中序顺序存到下标从1开始的数组里
for (i = 1; i <= n; i++)
cin >> hou[i];
stati = n; //给静态变量一个起始值,我这里用的是先构造右子树的递归所以给最后一个位置
for (i = 1; i <= n; i++)
cin >> zhong[i];
leaf* root = create(hou, zhong, 1, n);//构造二叉树
queue<leaf*> q; //用二叉树节点类型定义队列
q.push(root); //入队根节点
while (!q.empty()) { //每回判断队是否为空
leaf* temp = q.front(); //得到队头元素
cout << temp->data;
q.pop(); //出队
if (!temp->lchild) //如果左孩子为空就跳到右孩子判断
goto a;
q.push(temp->lchild);
a:if (!temp->rchild)
goto b;
q.push(temp->rchild);
b:if (!q.empty()) {
cout << " ";
}
}
cout << endl;
return 0;
}
运行结果