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

二叉树的最近公共祖先

使用dfs求解,根据返回值判断是否存在节点。返回值如果是空,表明当前子树不存在p或q。把p和q分为两种情况,一种是在p或q在当前节点,或者p或q分别在当前节点的左右子树上。

如果当前节点是p或者q,返回当前节点。

struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if(root==NULL||root==p||root==q){
        return root;
    }
    struct TreeNode* left_res=lowestCommonAncestor(root->left,p,q);
    struct TreeNode* right_res=lowestCommonAncestor(root->right,p,q);
    if(left_res==NULL){
        return right_res;
    }
    if(right_res==NULL){
        return left_res;
    }
    return root;
}

你可能感兴趣的:(leetcode,算法,职场和发展)