2020年3月PAT甲级满分必备刷题技巧
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, a binary tree can be uniquely determined.
Now given a sequence of statements about the structure of the resulting tree, you are supposed to tell if they are correct or not. A statment is one of the following:
Note:
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 no more than 10^3 and are separated by a space.
Then another positive integer M (≤30) is given, followed by M lines of statements. It is guaranteed that both A and B in the statements are in the tree.
For each statement, print in a line Yes if it is correct, or No if not.
9
16 7 11 32 28 2 23 8 15
16 23 7 32 11 2 28 15 8
7
15 is the root
8 and 2 are siblings
32 is the parent of 11
23 is the left child of 16
28 is the right child of 2
7 and 11 are on the same level
It is a full tree
Yes
No
Yes
No
Yes
Yes
Yes
1.postorder and inorder traversal sequences
给定后序和中序,这个是PAT甲级题库中很常见的知识点“二叉树的遍历”,可以参考《算法笔记》9.2节和题库的1086、1119、1138。
2.因为可能不是完全二叉树,同时输出的东西也挺复杂的,所以应该果断用DFS建二叉树。建树方法略有不同于1135(https://www.liuchuo.net/archives/4099),是采用map和结构体。
3.本题有7种输出,对应7个数据,都可以在DFS建树中体现:
(1)root,建树的返回就是root的值
(2)siblings,等价于两个节点的祖先是同一个
(3)parent,每个节点存父亲的值
(4)leftchild,A节点的左孩子是B,为了访问A的时候就能读出B节点的值,要用map和结构体
(5)rightchild,B节点的左孩子是A
(6)same level,记录节点的深度
(7)full tree,记录节点有没有左右孩子
来源致谢:https://blog.csdn.net/lianwaiyuwusheng/article/details/88084378
#include
#include
#include
#include
#include