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.

C++:
01 Node* commonAncestor(Node* head, Node* a, Node* b)
02 {
03     if(!(head&&a&&b))
04         return NULL;
05     if(((head->value>a->value)^(head->value>b->value))||(head==a)||(head==b))
06         return head;
07     if(head->value>a->value)
08         return commonAncestor(head->left,a,b);
09     else
10         return commonAncestor(head->right,a,b);
11 }
Advertisements
This entry was posted in Binary search, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s