1143 Lowest Common Ancestor (30 分)

本文介绍了一种解决二叉搜索树最低公共祖先(LCA)问题的算法,利用先序遍历构建二叉搜索树,并通过递归查找LCA。代码实现包括树的创建、LCA查找及错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:给定一个二叉搜索树的先序遍历,求两个结点的最低公共祖先

解题思路:二叉搜索树的中序遍历为排好序的序列,所以只有先序也可建树;直接根据二叉搜索树的先序序列逐个插入也可建树。最低公共祖先的查找根据高度来判断,和1151 LCA in a Binary Tree (30 分)差不多。也可以看看当初的代码。但有更方便的方法。

AC代码:

#include<iostream>
#include<unordered_map>
#include<algorithm>
#include<unordered_set>
#include<string>
using namespace std;
#define MAX 10005
int pre[MAX],in[MAX],N,M;

typedef struct node{
    int left,right;
}node;
unordered_map<int,node>arr;
void CreatBST(int preL,int inL,int inR)
{
    if(inL>inR)return ;
    int i=inL;
    while(pre[preL]!=in[i])++i;
    if(i-inL)arr[pre[preL]].left=pre[preL+1];
    else arr[pre[preL]].left=0;
    if(inR-i)arr[pre[preL]].right=pre[preL+i-inL+1];
    else arr[pre[preL]].right=0;
    CreatBST(preL+1,inL,i-1);
    CreatBST(preL+i-inL+1,i+1,inR);
}
void findLCA(int v,int a,int b)
{
    if(a==v)printf("%d is an ancestor of %d.\n",a,b);
    else if(b==v)printf("%d is an ancestor of %d.\n",b,a);
    else if(a<v&&b>v||a>v&&b<v)printf("LCA of %d and %d is %d.\n",a,b,v);
    else if(a<v&&b<v)findLCA(arr[v].left,a,b);
    else findLCA(arr[v].right,a,b);
}
int main()
{
    //freopen("test.txt","r",stdin);
    int i,u,v,root;
    scanf("%d %d",&M,&N);
    for(i=0;i<N;++i){
        scanf("%d",&pre[i]);
        if(i==0)root=pre[0];
        in[i]=pre[i];
    }
    sort(in,in+N);
    CreatBST(0,0,N-1);
    while(M--){
        scanf("%d %d",&u,&v);
        if(!arr.count(u)&&!arr.count(v))printf("ERROR: %d and %d are not found.\n",u,v);
        else if(!arr.count(u)||!arr.count(v))printf("ERROR: %d is not found.\n",arr.count(u)?v:u);
        else findLCA(root,u,v);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值