PAT甲级真题 1020 Tree Traversals (25分) C++实现(由后序、中序求层次遍历,队列模拟递归)

通过给定的二叉树后序和中序遍历序列,利用队列模拟递归求解层次遍历。首先找到根节点,然后递归处理左右子树,将子树根节点及其参数入队,依次输出层次遍历序列。代码实现详细解析层次遍历与递归的关系。
摘要由CSDN通过智能技术生成

题目

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

思路

又用了三个小时,智商堪忧…基础知识需要好好复习了,光是根据测试样例找出对应的树就花了好一阵子。

首先搞清术语:
postorder:后序
inorder:中序
level order:层次
preorder:前序

已知后序和中序数列,求相应的层次序列,方法是:

  1. 后序数列中最后一个元素必是根;
  2. 在中序数列中找到根的位置,根左侧的部分即是左子树的中序数列,根右侧的部分即是右子树的中序数列;
  3. 回到后序数列,从最后一个元素向前数右子数个数的数列,即是右子树的后序数列;再向前数左子树个数的数列,即是左子树的后序数列;
  4. 有了左右子树的后序、中序数列,递归求解即可。

为了按层次顺序输出,借助队列,将左、右子树的根连带其对应参数(用结构体记录)分别入队,分别输出当前左、右子树的根的值。队列初始化为post数组最右元素,其对应参数为in数组首尾位置;每次对队头元素进行操作,直到队列为空为止。

用结构体保存参数,逐个压入队列执行操作,相当于实现了队列版的递归(普通递归是使用栈)。

还得学习柳神代码,打好基础:1020. Tree Traversals (25)-PAT甲级真题

代码

#include <iostream>
#include <vector>
#include <queue>
using namespace s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值