PAT A1020. Tree Traversals (25) [⼆叉树的遍历,后序中序转层序]

给定一棵二叉树的后序和中序遍历序列,通过算法转换输出其层序遍历序列。题目假设所有键值都是互不相等的正整数。通过结合后序和中序遍历,并利用一个变量记录节点在二叉树中的位置,可以不构造二叉树直接得到层序遍历顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder
traversal sequences, you are supposed to output the level order traversal sequence of the corresponding
binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the
total number of nodes in the binary tree. The second line gives the postorder sequence and the third line
gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree.
All the numbers in a line must be separated by exactly one space, and there must be no extra space at the
end of the line.
Sample Input:
7 总结点数
2 3 1 5 7 6 4 后续
1 2 3 4 5 6 7中序
Sample Output:
4 1 6 3 5 7 2层序

题⽬⼤意:给定⼀棵⼆叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这⾥假设键值都是
互不相等的正整数。
分析:与后序中序转换为前序的代码相仿(⽆须构造⼆叉树再进⾏⼴度优先搜索),只不过加⼀个
变量index,表示当前根结点在⼆叉树中所对应的下标(从0开始),所以进⾏⼀次输出先序的递归的
时候,把节点的index和value放进结构体⾥,再装进容vector⾥,这样在递归完成后, vector中按照
index排序就是层序遍历的顺序。
如何后序和中序转换为先序,参考:https://www.liuchuo.net/archives/2090

#include <cstdio>
#include<iostream>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
const int maxn = 31;
struct node {
	int data;
	node* lchild;
	node* rchild;
};
int pre[maxn], in[maxn], post[maxn];	//先序 中序 后序 存储 
int n;								//结点总数
node* creat(int postL, int postR, int inL, int inR) {
	if (postL > postR)return NULL;		//后序序列长度<=0返回 
	node* root = new node;
	root->data = post[postR];		//后序最右为当前的根
	int k = inL;
	for (k; k <= inR; k++)
		if (in[k] == post[postR])	break;  //找到中序的根,退出循环 
	int numLeft = k - inL;
	root->lchild = creat(postL, postL + numLeft - 1, inL, k - 1);
	root->rchild = creat(postL + numLeft, postR - 1, k + 1, inR);
	return root;
}
int num = 1;					//输出空格标志位 
void BFS(node* root) {
	queue<node*>q;
	q.push(root);
	while (!q.empty()) {
		node* node = q.front();
		q.pop();
		cout << node->data;
		if (num != n)cout << " ";
		num++;
		if (node->lchild != NULL)q.push(node->lchild);
		if (node->rchild != NULL)q.push(node->rchild);
	}
}

int main() {
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> post[i];
	for (int i = 0; i < n; i++)
		cin >> in[i];

	node* root = creat(0, n - 1, 0, n - 1);   //建树
	BFS(root);								//层序输出(广度优先搜索 ) 
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值