PAT-Advanced-1020. Tree Traversals

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:

Sample Output:

似乎是 2016-02-06 做的,在博客上补上来吧……假期里真的是什么都没干,真颓废。

(幸好当时写了注释……

用了一个偷懒的解法:

后序遍历的顺序是 左子树->右子树->节点
中序遍历的顺序是 左子树->节点->右子树

那么对于任意一个节点,它的后序遍历的序列的最后一个元素就是它本身,然后可以根据中序遍历的序列确定它左孩子
和右孩子节点的遍历序列,以此类推。

然后我又懒得用 Tree ,于是记录了各个节点的深度信息,依据深度的排序将中序遍历转为层序遍历(用后序的也可以)。

同理,前序遍历的顺序是 节点->左子树->右子树 ,
因而能通过前序、中序、后序中任意两种中顺序还原一颗二叉树。

代码如下:

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注