给定一棵二叉搜索树的先序遍历序列,要求你找出任意两结点的最近公共祖先结点(简称 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.
题解:先用map标记该节点是否在树上,然后先判断是否有祖先关系,然后再找LCA(找到一个节点u的地址,往上找father看其子节点是否有另一个节点v ,如果找到则返回节点值(一定会找到的,最坏是根节点么~~)
#include<bits/stdc++.h>
using namespace std;
struct node
{
node *l,*r,*f;
int data;
};
int a[10001];
map<int,int>mp;
node *create(int l,int r)
{
if(l>r)
return NULL;
node *root=new node;
root->data=a[l];
root->f=NULL;
root->l=root->r=NULL;
int i;
for(i=l+1; i<=r; i++)//根据二叉搜索树的性质建树,第一个大于等于根节点的包括其后面的肯定在右子树,其他在左子树
{
if(a[i]>=a[l])
break;
}
root->l=create(l+1,i-1);
if(root->l)//要特判是否为空
root->l->f=root;//标记father节点
root->r=create(i,r);
if(root->r)
root->r->f=root;
return root;
}
int Find(node *root,int x)//在以root为根的子树中是否查找到x
{
if(root)
{
if(root->data==x)
return 1;
if(x<root->data)
return Find(root->l,x);
else
return Find(root->r,x);
}
return 0;
}
int Find_F(node *root,int u,int v)//u是否是v的祖先
{
if(root)
{
if(root->data==u)
{
if(Find(root,v))//如果在u的子树中找到了v,即说明u是v的祖先
return 1;
return 0;
}
if(u<root->data)
return Find_F(root->l,u,v);
else
return Find_F(root->r,u,v);
}
return 0;
}
int Find_LCA(node *root,int x)//从第一个节点的地址向上找第二个节点的祖先
{
while(root->f)
{
root=root->f;
int r=Find(root,x);
if(r) //若找到。返回对应祖先节点值
return root->data;
}
return 0;
}
node *Find_POS(node *root,int x)//找到一个节点的位置,返回的是一个指针
{
if(root)
{
if(root->data==x)
return root;
if(x<root->data)
return Find_POS(root->l,x);
else
return Find_POS(root->r,x);
}
return NULL;
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
node *root=NULL;
for(int i=1; i<=m; i++)
{
scanf("%d",&a[i]);
mp[a[i]]++;//将其标记,看是否在树上
}
root=create(1,m);
for(int i=1; i<=n; i++)
{
int u,v;
scanf("%d%d",&u,&v);
if(!mp[u]&&!mp[v])//根据题意模拟即可
cout<<"ERROR: "<<u<<" and "<<v<<" are not found."<<endl;
else if(!mp[u])
cout<<"ERROR: "<<u<<" is not found."<<endl;
else if(!mp[v])
cout<<"ERROR: "<<v<<" is not found."<<endl;
else
{
int x=Find_F(root,u,v);
int y=Find_F(root,v,u);
if(x)
cout<<u<<" is an ancestor of "<<v<<"."<<endl;
else if(y)
cout<<v<<" is an ancestor of "<<u<<"."<<endl;
else
{
node *temp=Find_POS(root,u);//随便选一个就能过,不用判断谁高谁低了
int r=Find_LCA(temp,v);
cout<<"LCA of "<<u<<" and "<<v<<" "<<"is"<<" "<<r<<"."<<endl;
}
}
}
return 0;
}