236_lowest_common_ancester_of_a_binary_tree

Leetcode

236.二叉树的最近公共祖先

shaozkshaozk leetcode/236_lowest_common_ancester_of_a_binary_tree.cpp · 34 行 · 更新于 2026-09-16

// 236.二叉树的最近公共祖先
//
// 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
// 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”


unordered_map<int, TreeNode*> parent;
unordered_map<int, bool> vis;

void dfs(TreeNode* root) {
    if (!root) return;
    if (root->left) {
        parent[root->left->val] = root;
        dfs(root->left);
    }
    if (root->right) {
        parent[root->right->val] = root;
        dfs(root->right);
    }
}

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    parent[root->val] = nullptr;
    dfs(root);
    while (p) {
        vis[p->val] = true;
        p = parent[p->val];
    }
    while (q) {
        if (vis[q->val]) return q;
        q = parent[q->val];
    }
    return nullptr;
}

评论