【图论之最近公共祖先】最近公共祖先专题
求解方法:
二叉树的最近公共祖先(Lowest Common Ancestor)
北邮考研机试题
求两结点之间的最短路径长度
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1010;
int n, m;
int l[N], r[N], p[N];
int dist[N];
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);
}
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;
}
int main()
{
int T;
scanf("%d", &T);
while(T -- )
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i ++ )
{
int a, b;
scanf("%d%d", &a, &b);
l[i] = a, r[i] = b;
if(a != -1) p[a] = i;
if(b != -1) p[b] = i;
}
dfs(1, 0);
while(m -- )
{
int a, b;
scanf("%d%d", &a, &b);
int c = get_lca(a, b);
printf("%d\n", dist[a] + dist[b] - 2 * dist[c]);
}
}
return 0;
}
236. 二叉树的最近公共祖先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
auto left = lowestCommonAncestor(root->left, p, q);
auto right = lowestCommonAncestor(root->right, p, q);
if (!left) return right;
if (!right) return left;
return root;
}
};
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程