代码改变世界

Lowest Common Ancestor of a Binary Search Tree (BST)

2014-12-16 23:39  李涛的技术博客  阅读(155)  评论(0)    收藏  举报

Given a binary search tree(BST), find the lowest common ancestor of two given nodes in the BST.

 

Node* LCA(Node* root, Node* p, Node* q)
{
    if (!root || !p || !q)
        return NULL;
    if (max(p->data, q->data) < root->data)
        return LCA(root->left, p, q);
    else if (min(p->data, q->data) < root->data)
        return LCA(root->right, p, q);
    else
        return root;
}