Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.

 1 bool covers(Node *root,Node *p)
 2 {
 3     if(!root) return false;
 4     if(root==p) return true;
 5     return covers(root->left,p)||covers(root->right,p);
 6 }
 7 
 8 Node * commonFather(Node *root,Node *p,Node *q)
 9 {
10     if(covers(root->left,p)&&covers(root->left,q))
11         return commonFather(root->left,p,q);
12     if(covers(root->right,p)&&covers(root->right,q))
13         return commonFather(root->right,p,q);
14     return root;
15 }

 

 posted on 2013-08-07 16:52  xuanxu  阅读(173)  评论(0编辑  收藏  举报