首页 > 代码库 > Lowest Common Ancestor of a Binary Search Tree (BST)

Lowest Common Ancestor of a Binary Search Tree (BST)

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        return LCA(root->right, p, q);    else        return root;}

 

Lowest Common Ancestor of a Binary Search Tree (BST)