给定一棵二叉搜索树的先序遍历序列,要求你找出任意两结点的最近公共祖先结点(简称 LCA)。
输入格式:
输入的第一行给出两个正整数:待查询的结点对数 M(≤ 1 000)和二叉搜索树中结点个数 N(≤ 10 000)。随后一行给出 N 个不同的整数,为二叉搜索树的先序遍历序列。最后 M 行,每行给出一对整数键值 U 和 V。所有键值都在整型int范围内。
输出格式:
对每一对给定的 U 和 V,如果找到 A
是它们的最近公共祖先结点的键值,则在一行中输出 LCA of U and V is A.
。但如果 U 和 V 中的一个结点是另一个结点的祖先,则在一行中输出 X is an ancestor of Y.
,其中 X
是那个祖先结点的键值,Y
是另一个键值。如果 二叉搜索树中找不到以 U 或 V 为键值的结点,则输出 ERROR: U is not found.
或者 ERROR: V is not found.
,或者 ERROR: U and V are not found.
。
输入样例:
6 8
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99
输出样例:
LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.
思路
因为是二叉搜索树所以可以直接用其先序遍历建树(不过效率貌似没有先+中块)
然后,查找最近公共祖先,一开始想的是child->parent回溯,然后超时了
仔细思考了一下,发现搜索树上任意两点X,Y(X<=Y)
其共同祖Z先必定满足 Z>=X and Z<=Y
而最近公共祖先,必定是二分查找时,最先符合上述要求的那个数
#include<bits/stdc++.h>
using namespace std;
struct Tree{
int data,left,right;
}tree[10001]; // root = 1
map<int,int> Index; // Index[num]:映射获得num对应Tree上的节点下标,映射为0表示不存在
void createTree(int parent,int child);
int OP(int x,int y);
int main()
{
int M,N;
cin >> M >> N >> tree[1].data;
Index[tree[1].data] = 1;
for(int z=2;z<=N;z++){
scanf("%d",&tree[z].data);
Index[tree[z].data] = z;
createTree(1,z);
}
while(M--){
int U,V;
scanf("%d %d",&U,&V);
if(Index[U]==0 && Index[V]==0) printf("ERROR: %d and %d are not found.\n",U,V);
else if(Index[U]==0) printf("ERROR: %d is not found.\n",U);
else if(Index[V]==0) printf("ERROR: %d is not found.\n",V);
else
{
int flag = OP(U,V);
if(flag==U) printf("%d is an ancestor of %d.\n",U,V);
else if(flag==V) printf("%d is an ancestor of %d.\n",V,U);
else printf("LCA of %d and %d is %d.\n",U,V,flag);
}
}
return 0;
}
void createTree(int parent,int child)
{
if(tree[parent].data>tree[child].data){
if(tree[parent].left==0){
tree[parent].left = child;
return;
}
createTree(tree[parent].left,child);
}else{
if(tree[parent].right==0){
tree[parent].right = child;
return;
}
createTree(tree[parent].right,child);
}
}
int OP(int x,int y)
{
if(x==y) return x;
if(x>y) {
int temp = x;
x = y;
y = temp;
}
int lca = 1,val=tree[1].data;
while (true){
if(val>= x && val<=y) return val;
if(val<x) lca = tree[lca].right;
else lca = tree[lca].left;
val = tree[lca].data;
}
}