后序+中序=树
1. 原文
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:
A is the root
A and B are siblings
A is the parent of B
A is the left child of B
A is the right child of B
A and B are on the same level
It is a full tree
Note:
Two nodes are on the same level, means that they have the same depth.
A full binary tree is a tree in which every node other than the leaves has two children.
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 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.
Output Specification
For each statement, print in a line Yes if it is correct, or No if not.
Sample Input
1 | 9 |
Sample Output
1 | Yes |
2. 解析思路
根据后序+中序建立树,记录结点之间的位置关系
node* tree[1010] 值对应结点
int siblings[1010] 分别保存左结点,右结点数值
int level[1010] 保存结点所在层数
输入技巧:sscanf(str.c_str(),”%d is the root”,&num); 直接取出对应数值
3. AC代码
1 |
|