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

发布时间 2023-04-11 16:47:15作者: xiazichengxi

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

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

class Solution {
public:
    bool post_i(TreeNode* cur, TreeNode* p, TreeNode* q){
        if(cur == nullptr) return false;
        bool left = post_i(cur->left,p,q);
        bool right = post_i(cur->right,p,q);
        if(p == cur || q == cur) {
            if(left||right) res = cur;
            return true;
        }
        if(left&&right){
            res = cur;
        }
        return left|right;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        post_i(root,p,q);
        return res;
    }
private:
    TreeNode* res = nullptr;
};