题目
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:前序
已知后序和中序数列,求相应的层次序列,方法是:
- 后序数列中最后一个元素必是根;
- 在中序数列中找到根的位置,根左侧的部分即是左子树的中序数列,根右侧的部分即是右子树的中序数列;
- 回到后序数列,从最后一个元素向前数右子数个数的数列,即是右子树的后序数列;再向前数左子树个数的数列,即是左子树的后序数列;
- 有了左右子树的后序、中序数列,递归求解即可。
为了按层次顺序输出,借助队列,将左、右子树的根连带其对应参数(用结构体记录)分别入队,分别输出当前左、右子树的根的值。队列初始化为post数组最右元素,其对应参数为in数组首尾位置;每次对队头元素进行操作,直到队列为空为止。
用结构体保存参数,逐个压入队列执行操作,相当于实现了队列版的递归(普通递归是使用栈)。
还得学习柳神代码,打好基础:1020. Tree Traversals (25)-PAT甲级真题
代码
#include <iostream>
#include <vector>
#include <queue>
using namespace s