题目
https://pintia.cn/problem-sets/994805342720868352/problems/994805343727501312
题意
给出一棵树的前序序列,判断两个节点的最近公共祖先(LCA)
题目解析
通过map<int,int>判断节点是否在树中
遍历前序序列,判断当前根节点是否符合祖先节点的特点(左右一大一小,或者就是待测的两个节点之一),找到了退出循环输出即可
注意,因为这颗树是BST,才能符合这个搜索逻辑
AC代码
#include<bits/stdc++.h>
using namespace std;
int m,n,t,x,y,pre[10001];
map<int,int> vis;
int main()
{
scanf("%d %d",&m,&n);
for(int i=0;i<n;i++)
{
scanf("%d",&pre[i]);
vis[pre[i]]=1;
}
while(m--)
{
scanf("%d %d",&x,&y);
for(int i=0;i<n;i++)
{
t=pre[i];
if( (t>x&&t<y) || (t<x&&t>y) || t==x || t==y ) break;
}
if(!vis[x]&&!vis[y])
printf("ERROR: %d and %d are not found.\n",x,y);
else if(!vis[x]||!vis[y])
printf("ERROR: %d is not found.\n",!vis[x]?x:y);
else if(t==x)
printf("%d is an ancestor of %d.\n",x,y);
else if(t==y)
printf("%d is an ancestor of %d.\n",y,x);
else
printf("LCA of %d and %d is %d.\n",x,y,t);
}
}
参考
PAT 1143. Lowest Common Ancestor (30) – 甲级(强烈推荐去看一看,思路真的特别好,柳神强啊!)