Closest common ancester

Given two pointers of nodes in a binary tree, find the closest common ancestor. Each node only has two pointers, left and right. 

C++:
01 Node* FindCommonAncester(Node* head, Node* A, Node* B)
02 {
03     if(head==NULL)
04         return NULL;
05     if((head==A)||(head==B))
06         return head;
07     Node* tmpl=NULL;
08     Node* tmpr=NULL;
09     tmpl=FindCommonAncester(head->left,A,B);
10     tmpr=FindCommonAncester(head->right,A,B);
11     if(tmpl==NULL)
12         return tmpr;
13     if(tmpr==NULL)
14         return tmpl;
15     return head;
16 }
Advertisements
This entry was posted in 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