第十一天PAT-A1143 Lowest Common Ancestor基于二叉排序树中序序列的LCA算法

该博客介绍了如何使用二叉排序树的中序序列特性来解决寻找最近公共祖先的问题。通过先序序列排序得到中序序列,根据节点在根节点两侧的情况进行判断,递归遍历以找到LCA。关键在于正确建立先序序列和中序序列的映射关系。

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

A1143

Description:

给出二叉排序树的先序序列,求任意两节点的最近公共祖先;

算法描述:

  • 二叉排序树中序序列特性即是递增序列,将先序序列排序即可得中序序列;
  • 如果两个节点位于根节点的两侧,则该根节点即为最近公共祖先;
  • 若两个节点均位于根节点单侧,则递归遍历该子树;
  • 注意映射关系不要写错了,比如代码中第17行获取先序序列下标是用mp映射,第一遍写的时候写成了in[pre[preRoot]]…
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<unordered_map>
#include<vector>
#include<queue>
using namespace std;
unordered_map<int,int>mp;   //数值-in下标映射
vector<int>pre, in;
int n, m, u, v;
void lca(int inL, int inR, int preRoot){
    if(inL > inR) return ;
    int inRoot = mp[pre[preRoot]];
    if(u<pre[preRoot]&&v<pre[preRoot])
        lca(inL, inRoot-1, preRoot+1);
    else if(u>pre[preRoot]&&v>pre[preRoot])
        lca(inRoot+1, inR, preRoot+1);
    else if(u == pre[preRoot])
        printf("%d is an ancestor of %d.\n", u, v);
    else if(v == pre[preRoot])
        printf("%d is an ancestor of %d.\n", v, u);
    else if((u<pre[preRoot]&&v>pre[preRoot])||(u>pre[preRoot]&&v<pre[preRoot]))
        printf("LCA of %d and %d is %d.\n", u, v, pre[preRoot]);
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    scanf("%d%d", &m, &n);
    pre.resize(n+1), in.resize(n+1);
    for(int i = 1; i <= n; i++){
        scanf("%d", &pre[i]);
        in[i] = pre[i];
    }
    sort(in.begin()+1, in.end());
    for(int i = 1; i <= n; i++){
        mp.insert(make_pair(in[i], i));
    }
    for(int i = 1; i <= m; i++){
        scanf("%d%d", &u, &v);
        if(mp.count(u)==0&&mp.count(v)==0)
            printf("ERROR: %d and %d are not found.\n", u, v);
        else if((mp.count(u)!=0&&mp.count(v)==0)||(mp.count(u)==0&&mp.count(v)!=0))
            printf("ERROR: %d is not found.\n", mp.count(u)==0?u:v);
        else
            lca(1, n, 1);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值