二叉树 LCA

GitHub跳转原题关系图返回列表

后序返回是否找到 p/q;左右均找到则当前为 LCA。

OJ: leetcodecn

题目 ID: lowest-common-ancestor-of-a-binary-tree

难度:普及+/提高

标签:二叉树递归DFScpppython

日期: 2026-07-29 13:10

题意

找二叉树中两个节点的最近公共祖先(LCA)。

思路

后序 DFS:如果当前节点是 p 或 q 则返回自身;左右子树各返回一个非空结果则当前为 LCA;否则返回非空的一侧。

代码

cpp
#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left, *right;

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
        if (!root || root == p || root == q)
            return root;
        auto l = lowestCommonAncestor(root->left, p, q);
        auto r = lowestCommonAncestor(root->right, p, q);
        if (l && r)
            return root;
        return l ? l : r;
    }
};

TreeNode *build(istream &in, int n) {
    vector<TreeNode *> nodes(n);
    queue<TreeNode *> q;
    for (int i = 0, v; i < n; i++) {
        in >> v;
        if (v != -1)
            nodes[i] = new TreeNode(v);
    }
    TreeNode *root = nodes[0];
    if (root)
        q.push(root);
    int idx = 1;
    while (!q.empty() && idx < n) {
        auto cur = q.front();
        q.pop();
        if (idx < n) {
            cur->left = nodes[idx];
            if (nodes[idx])
                q.push(nodes[idx]);
            idx++;
        }
        if (idx < n) {
            cur->right = nodes[idx];
            if (nodes[idx])
                q.push(nodes[idx]);
            idx++;
        }
    }
    return root;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, pv, qv;
    cin >> n >> pv >> qv;
    auto r = build(cin, n);
    // find p, q nodes by value
    TreeNode *p = nullptr, *q = nullptr;
    queue<TreeNode *> bfs;
    bfs.push(r);
    while (!bfs.empty()) {
        auto cur = bfs.front();
        bfs.pop();
        if (!cur)
            continue;
        if (cur->val == pv)
            p = cur;
        if (cur->val == qv)
            q = cur;
        bfs.push(cur->left);
        bfs.push(cur->right);
    }
    cout << Solution().lowestCommonAncestor(r, p, q)->val << '\n';
    return 0;
}
python
#!/usr/bin/env python3
from collections import deque
from typing import Optional


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = self.right = None


class Solution:
    def lowestCommonAncestor(
        self, root: TreeNode, p: TreeNode, q: TreeNode
    ) -> TreeNode:
        if not root or root is p or root is q:
            return root
        l = self.lowestCommonAncestor(root.left, p, q)
        r = self.lowestCommonAncestor(root.right, p, q)
        if l and r:
            return root
        return l or r


def build(arr):
    if not arr:
        return None
    nodes = [TreeNode(v) if v != -1 else None for v in arr]
    q = deque([nodes[0]]) if nodes[0] else deque()
    idx = 1
    while q and idx < len(arr):
        cur = q.popleft()
        if idx < len(arr):
            cur.left = nodes[idx]
            if nodes[idx]:
                q.append(nodes[idx])
            idx += 1
        if idx < len(arr):
            cur.right = nodes[idx]
            if nodes[idx]:
                q.append(nodes[idx])
            idx += 1
    return nodes[0]


def main():
    n, pv, qv = map(int, input().split())
    a = list(map(int, input().split()))
    r = build(a)
    # find nodes
    st = [r]
    p = q = None
    while st:
        cur = st.pop()
        if not cur:
            continue
        if cur.val == pv:
            p = cur
        if cur.val == qv:
            q = cur
        st.append(cur.left)
        st.append(cur.right)
    print(Solution().lowestCommonAncestor(r, p, q).val)


if __name__ == "__main__":
    main()

复杂度

时间 O(n),空间 O(height)。

总结

LCA 的递归写法极其简洁,核心是"两侧都不空则当前是答案"。