1151 LCA in a Binary Tree (30 分)

该程序实现了一个寻找二叉树中两个节点最近公共祖先的算法。它使用前序遍历和中序遍历来构造树的映射,并通过深度优先搜索找到最近公共祖先。输入包括树的节点数、节点值、前序遍历和中序遍历的序列,以及要查找的两个节点。如果节点不存在,程序会输出错误信息。

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

1151 LCA in a Binary Tree (30 分)

#include <iostream>
#include <map>
using namespace std;
map<int, int> m;
int pre[10010], in[10010], n, M, x, y;
void dfs(int root, int l1, int l2) {
	if(l1 > l2) return;
	int proot = m[pre[root]], px = m[x], py = m[y];
	if(px < proot && py < proot)
		dfs(root + 1, l1, proot - 1);
	else if(px < proot && py > proot || px > proot && py < proot)
		printf("LCA of %d and %d is %d.\n", x, y, pre[root]);
	else if(px > proot && py > proot)
		dfs(root + proot - l1 + 1, proot + 1, l2);
	else if(px == proot)
		printf("%d is an ancestor of %d.\n", x, y);
	else if(py == proot)
		printf("%d is an ancestor of %d.\n", y, x);
}
int main() {
	cin >> M >> n;
	for(int i = 1; i <= n; ++i){
		cin >> in[i];
		m[in[i]] = i;
	}
	for(int i = 1; i <= n; ++i)
		cin >> pre[i];
	while(M--) {
		cin >> x >> y;
		if(m[x] == 0 && m[y] == 0)
			printf("ERROR: %d and %d are not found.\n", x, y);
		else if(m[x] == 0 || m[y] == 0)
			printf("ERROR: %d is not found.\n", m[x] == 0 ? x : y);
		else
			dfs(1, 1, n);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值