代码改变世界

二叉树最近公共祖先

2020-11-29 01:45  woshihuangrulin  阅读(85)  评论(0编辑  收藏  举报

二叉树最近祖先,使用递归方法,满足左子树和右子树都找到,或者某一个节点作为根结点而它的子节点包含另一个目标节点

 

class Solution {
    TreeNode* ancestor;
    bool find_ancestor = false;
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        searchNodes(root, p, q);
        return ancestor;
    }

    bool searchNodes(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == nullptr) {
            return false;
        }
        bool lson = searchNodes(root->left, p, q);
        bool rson = searchNodes(root->right, p, q);

        if ((lson && rson) || ((root == p || root == q) && (lson || rson))) {
            ancestor = root;
            return false;
        }

        return lson || rson || root == p || root == q;
    }
};