236. Lowest Common Ancestor of a Binary Tree

采用递归,分别在左子树和右子树里面查找,如果都能找到,当前节点就是最近共同祖先
如果只能在一个树找到,说明这个数就是最近共同祖先

struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    
    
    if(root == NULL || root == p || root == q)
        return root;

    struct TreeNode *left = lowestCommonAncestor(root->left, p,q);
    struct TreeNode *right = lowestCommonAncestor(root->right, p,q);

    if(left&&right)
        return root;
    if(left)
        return left;
    if(right)
        return right;

    return NULL;
    

}

你可能感兴趣的:(236. Lowest Common Ancestor of a Binary Tree)