PAT 1151 LCA in a Binary Tree——原理很简单,处理起来很麻烦

本文深入解析了LCA(最近公共祖先)算法的实现原理,通过分析前序和中序遍历序列,阐述了如何判断两个节点是否存在公共祖先,并详细解释了在不按序列顺序输入节点时,如何调整顺序以正确找到最近公共祖先。文章提供了完整的C++代码实现,展示了如何处理节点未找到的情况。

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

分析

找得到

LCA of 2 and 6 is 3.

8 is an ancestor of 1.

找不到

ERROR: 9 is not found.

ERROR: 12 and -3 are not found.

找不到——》任意前序/中序搜索即可

找得到:

LCA of 2 and 6 is 3.

分析中序可知:祖先3必在2,6中间

分析前序可知:祖先3必在2,6前面

因此同时满足上述2点,则说明能找到祖先

当不满足时,则说明情况为8 is an ancestor of 1.

具体实现

实际实现最大问题:题目不会按照 序列的顺序给出

比如2,6是按照序列顺序给的

题目会给6,2

因此问题在于调序——按照序列顺序处理

其次,最后输出时还得按照题目给出顺序进行输出

代码

#include<bits/stdc++.h>
using namespace std;

int pairs, quantity, x, y;
vector<int>preorder, inorder;
map<int, int>pre_id, in_id;

void Judge(map<int, int>::iterator, map<int, int>::iterator, int, int);
void AdjustOrder(map<int, int>::iterator&, map<int, int>::iterator&);
int main() {
	scanf("%d %d", &pairs, &quantity);
	inorder.resize(quantity);
	for (int i = 0; i < quantity; i++) {
		scanf("%d", &x);
		inorder[i] = x;
		in_id[x] = i;
	}
	preorder.resize(quantity);
	for (int i = 0; i < quantity; i++) {
		scanf("%d", &x);
		preorder[i] = x;
		pre_id[x] = i;
	}
	for (int i = 0; i < pairs; i++) {
		scanf("%d %d", &x, &y);
		auto x_pre_id = pre_id.find(x);
		auto y_pre_id = pre_id.find(y);
		if (x_pre_id == pre_id.end() || y_pre_id == pre_id.end()) {
			if (x_pre_id == pre_id.end() && y_pre_id == pre_id.end()) {
				printf("ERROR: %d and %d are not found.\n",x,y);
				continue;
			}
			printf("ERROR: %d is not found.\n", x_pre_id == pre_id.end() ? x : y);
			continue;
		}
		auto x_in_id = in_id.find(x);
		auto y_in_id = in_id.find(y);
		AdjustOrder(x_in_id, y_in_id);
		AdjustOrder(x_pre_id, y_pre_id);
		Judge(x_pre_id, y_pre_id, x_in_id->second, y_in_id->second);
	}
	return 0;
}
void Judge(map<int, int>::iterator front, map<int, int>::iterator back,int in_front,int in_back) {
	if (in_front + 1 != in_back) {
		for (int i = 0; i < front->second; i++) {
			auto j = in_id.find(preorder[i]);
			if ( j->second <in_back && j->second>in_front) {
				printf("LCA of %d and %d is %d.\n", x, y, j->first);
				return;
			}
		}
	}
	printf("%d is an ancestor of %d.\n", front->first, back->first);
}
void AdjustOrder(map<int, int>::iterator& x, map<int, int>::iterator& y) {
	if (x->second > y->second) {
		swap(x, y);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值