代码随想录:二叉树的公共祖先

这道题是真巧妙,巧妙有两点

  1. 不用区分两个目标节点,只要命中了,就往上
  2. 代码可以处理一个节点本来就是另一个节点祖先的情况
/**
 * 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 == NULL)
            return NULL;
        if (root == p || root == q)
            return root;

        TreeNode* l = lowestCommonAncestor(root->left, p, q);
        TreeNode* r = lowestCommonAncestor(root->right, p, q);

        if (l != NULL && r != NULL)
            return root; // 找到最近公共祖先
        if (l != NULL && r == NULL)
            return l;
        if (l == NULL && r != NULL)
            return r;

        return NULL;
    }
};
posted @ 2025-01-18 20:26  huigugu  阅读(7)  评论(0)    收藏  举报