寻找两结点的共同祖先
1. 原文
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 1,000), the number of pairs of nodes to be tested; and N (≤ 10,000), the number of keys in the binary tree, respectively. In each of the following two lines, N distinct integers are given as the inorder and preorder traversal sequences of the binary tree, respectively. It is guaranteed that the binary tree can be uniquely determined by the input sequences. Then M lines follow, each contains a pair of integer keys U and V. All the keys are in the range of int
output Specification:
For each given pair of U and V, print in a line LCA of U and V is A.
if the LCA is found and A
is the key. But if A
is one of U and V, print X is an ancestor of Y.
where X
is A
and Y
is the other node. If U or V is not found in the binary tree, print in a line ERROR: U is not found.
or ERROR: V is not found.
or ERROR: U and V are not found.
.
Sample Input:
1 | 6 8 |
Sample output:
1 | LCA of 2 and 6 is 3. |
2. 解析
记录出现过的值 –> map<int,int> exist; 使用数组会超时,N个结点的值并不是1-N
树的中序inorder记录了结点的树结构 左 根 右 –> 记录值出现顺序 exist[in[i]]=i;
树的先序preorder最先出现的必是结点根root
中序+先序=树
查找u, v,root的位置:
- u<root并且v<root 则u,v的根在当前根的左子树
- u>root并且v<root 或u<root并且v>root,两者刚好在根的两侧,当前根即为Ancestor
- u>root并且v>root 则u,v的根在当前根的右子树
3. AC代码
1 |
|
exist设为map,结点的值并不在[0,10000]内