PAT TOP 1006 Tree Traversals - Hard Version (35)

该博客讨论了PAT(编程能力测试)的一道题目,即如何从给定的不完整二叉树的中序、前序和后序遍历中重建完整的树结构。博主分享了两种不同的深度优先搜索(DFS)算法策略,但都存在局限性。第一种算法因时间复杂度过高导致在最后一个测试用例超时,而第二种算法在特定n值(如100)时能通过部分测试点。博主通过混合两种不完全正确的算法成功通过了该题的验证。
摘要由CSDN通过智能技术生成

问题描述:

1006 Tree Traversals - Hard Version (35 分)

Given the partial results of a binary tree's traversals in in-order, pre-order, and post-order. You are supposed to output the complete results and the level order traversal sequence of the corresponding tree.

Input Specification:

Each input file contains one test case. For each case, a positive integer N (≤100) is given in the first line. Then three lines follow, containing the incomplete in-order, pre-order and post-order traversal sequences, respectively. It is assumed that the tree nodes are numbered from 1 to N and no number is given out of the range. A -represents a missing number.

Output Specification:

For each case, print in four lines the complete in-order, pre-order and post-order traversal sequences, together with the level order traversal sequence of the corresponding tree. The numbers must be separated by a space, and there must be no extra space at the beginning or the end of each line. If it is impossible to reconstruct the unique tree from the given information, simply print Impossible.

Sample Input 1:

9
3 - 2 1 7 9 - 4 6
9 - 5 3 2 1 - 6 4
3 1 - - 7 - 6 8 -

Sample Output 1:

3 5 2 1 7 9 8 4 6
9 7 5 3 2 1 8 6 4
3 1 2 5 7 4 6 8 9
9 7 8 5 6 3 2 4 1

Sample Input 2:

3
- - -
- 1 -
1 - -

Sample Ou

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值