树的公共祖先

// lca_bst
node *lca_bst(node *n, node *p, node *q) {
    if((n->val - p->val) * (n->val - q->val) <= 0) return n;
    else if(n->val < p->val && n->val < q->val) return lca_bst(n->right, p, q);
    else return lca_bst(n->left, p ,q);
}
// lca_common
node* lca_common(node *n, node *p, node *q) {
    if (n == NULL) return NULL;
    if (n->val == p->val || n->val == q->val) return n;
    node *left = lca_common(n->left, p, q);
    node *right = lca_common(n->right, p, q);
    if (left != NULL && right != NULL) return n;
    if (left != NULL) return left;
    if (right != NULL) return right;
    return NULL;
}
posted @ 2020-04-11 00:22  SteveYu  阅读(245)  评论(0编辑  收藏  举报