Leetcode刷题笔记(c++)_热题 HOT 100_236. 二叉树的最近公共祖先

递归

class Solution {
public:
    TreeNode* out;
    bool dfs(TreeNode* root, TreeNode* p, TreeNode* q){
        if(!root)return 0;
        bool left=dfs(root->left,p,q);
        bool right=dfs(root->right,p,q);
        if((left&&right)||((root->val==p->val||root->val==q->val)&&(left||right))){
            out=root;
        }
        return left||right||root->val==p->val||root->val==q->val;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root,p,q);
        return out;        
    }
};

Leetcode刷题笔记(c++)_热题 HOT 100_236. 二叉树的最近公共祖先_第1张图片

你可能感兴趣的:(leetcode,c++,深度优先)