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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义