ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【二叉树】最近公共祖先专题

2022-09-05 11:32:17  阅读:193  来源: 互联网

标签:专题 TreeNode 祖先 return int right 二叉树 dist root


最近公共祖先(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;
    }
};

标签:专题,TreeNode,祖先,return,int,right,二叉树,dist,root
来源: https://www.cnblogs.com/Tshaxz/p/16657493.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有