其他分享
首页 > 其他分享> > 【二叉树】最近公共祖先专题

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

作者:互联网

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