剑指 Offer 68 - II. 二叉树的最近公共祖先(简单)

发布时间 2023-08-26 20:31:09作者: 孜孜不倦fly

题目:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==p||root==q||root==nullptr) return root;      //如果当前节点为空或者当前节点即为其中某个指定节点
        TreeNode* left = lowestCommonAncestor(root->left, p, q);      
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if(left&&right) return root;
        if(!left) return right;
        return left;
    }
};

以上代码转自代码随想录