Acwing 3555. 二叉树 java 最近公共祖先

😋 原题地址
在这里插入图片描述
在这里插入图片描述

1
8 4
2 3
4 5
6 -1
-1 -1
-1 7
-1 -1
8 -1
-1 -1
1 6
4 6
4 5
8 1

输出样例

2
4
2
4

🤠 LCA 求二叉树两点之间的距离 (d[ ] 是节点到 root 节点的距离,dfs预处理)

在这里插入图片描述
🤠 O(nm)

import java.io.*;
import java.util.*;

public class Main
{
	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

	static int N = 1010, n, m, t;
	static int[] p = new int[N];
	static int[] l = new int[N];
	static int[] r = new int[N];
	static int[] dist = new int[N];// 维护到根节点的距离

	public static void main(String[] args) throws IOException
	{
		t = Integer.parseInt(in.readLine());

		while (t-- > 0)
		{

			String[] split = in.readLine().split(" ");
			n = Integer.parseInt(split[0]);
			m = Integer.parseInt(split[1]);



//			输入 i 节点的左右儿子
			for (int i = 1; i <= n; i++)
			{
				String[] split2 = in.readLine().split(" ");
				int a = Integer.parseInt(split2[0]);
				int b = Integer.parseInt(split2[1]);
				l[i] = a;
				r[i] = b;
				if (a != -1)
					p[a] = i;
				if (b != -1)
					p[b] = i;
			}
//			dfs 预处理距离数组
			dfs(1, 0);

			for (int i = 0; i < m; i++)
			{
				String[] split2 = in.readLine().split(" ");
				int a = Integer.parseInt(split2[0]);
				int b = Integer.parseInt(split2[1]);

				int par = get_lca(a, b);// 求最近的公共祖先
				int d = dist[a] + dist[b] - 2 * dist[par];
				System.out.println(d);
			}

		}

	}

	/**
	 * @param a
	 * @param b
	 * @return 返回 a b 最近的公共祖先
	 */
	private static int get_lca(int a, int b)
	{
		if (dist[a] < dist[b])
			return get_lca(b, a);
		while (dist[a] > dist[b])
			a = p[a];
		while (a != b)
		{
			a = p[a];
			b = p[b];
		}
		return a;
	}

	/**
	 * @param u 节点
	 * @param d 到根节点的距离
	 */
	private static void dfs(int u, int d)
	{
		dist[u] = d;
		if (l[u] != -1)
			dfs(l[u], d + 1);
		if (r[u] != -1)
			dfs(r[u], d + 1);
	}
}

posted @   兑生  阅读(12)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
Live2D
欢迎阅读『Acwing 3555. 二叉树 java 最近公共祖先』
点击右上角即可分享
微信分享提示