PAT--1151 LCA in a Binary Tree--LCA

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/1038430130011897856

题目大意:给定中序和先序,求给定两个点的最近公共祖先。

分析:假设给出的是a和b,若a和b在当前根节点的左子树上,那么就在当前根节点的左子树上找,同理,都在右子树上,就在当前根节点的右子树上找,如果一个左边,一个右边,那么答案就是当前根节点。

14行:inroot - l是左子树的节点数,所以先序数组肯定往右移动inroot - l,然后再加上当前根节点,所以再加1。

#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 5;
int n, m, in[N], pre[N];
map<int, int> pos;
void lca(int l, int r, int preroot, int a, int b) {
	if(l > r) return ;
	int inroot = pos[pre[preroot]], ain = pos[a], bin = pos[b];
	if(ain < inroot && bin < inroot) {
		lca(l, inroot - 1, preroot + 1, a, b);
	} else if((ain < inroot && bin > inroot) || (ain > inroot && bin < inroot)) {
		printf("LCA of %d and %d is %d.\n", a, b, in[inroot]);
	} else if(ain > inroot && bin > inroot) {
		lca(inroot + 1, r, preroot + 1 + inroot - l, a, b);
	} else if(ain == inroot) {
		printf("%d is an ancestor of %d.\n", a, b);
	} else if(bin == inroot) {
		printf("%d is an ancestor of %d.\n", b, a);
	}
}
int main() {
	scanf("%d %d", &m, &n);
	for(int i = 1; i <= n; i++) {
		scanf("%d", &in[i]);
		pos[in[i]] = i;
	}
	for(int i = 1; i <= n; i++)
		scanf("%d", &pre[i]);
	int a, b;
	while(m--) {
		scanf("%d %d", &a, &b);
		if(pos[a] == 0 && pos[b] == 0) {
			printf("ERROR: %d and %d are not found.\n", a, b);
		} else if(pos[a] == 0 || pos[b] == 0) {
			printf("ERROR: %d is not found.\n", pos[a] == 0 ? a : b);
		} else {
			lca(1, n, 1, a, b);
		}
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值