#include <iostream>
#include <vector>
using namespace std;
// 参考 http://blog.youkuaiyun.com/cxllyg/article/details/7635992
// 参考 《剑指offer》P256
struct node{
int data;
node *left;
node *right;
node(const int &x, node *l = NULL, node *r = NULL){
data = x;
left = l;
right = r;
}
~node(){}
};
bool node_path(node *p, node *root, vector<node *> &path){
if(root == NULL)
return false;
if(p == root){
path.push_back(root);
return true;
}
// 倒序保存
//if(node_path(p, root->left, path)){
// path.push_back(root);
// return true;
//}
//else if(node_path(p, root->right, path)){
// path.push_back(root);
// return true;
//}
//else {
// return false;
//}
// 顺序保存
path.push_back(root);
bool found = false;
if(node_path(p, root->left, path)){
found = true;
}
else if(node_path(p, root->right, path)){
found = true;
}
else {
found = false;
}
if(!found){
path.pop_back();
}
return found;
}
node *find_lowest_common_ancestor(node *p1, node *p2, node *root){
vector<node *> path1, path2;
bool find1 = node_path(p1, root, path1);
bool find2 = node_path(p2, root, path2);
if(!(find1 && find2))
return NULL;
node *ancestor = root;
// 倒序取最近共同祖先
//int max_common_len = path1.size() < path2.size() ? path1.size() : path2.size();
//for(int i = 0; i < max_common_len; ++i){
// if(path1[path1.size() - 1 - i] != path2[path2.size() - 1 - i])
// break;
// ancestor = path1[path1.size() - 1 - i];
//}
// 顺序取最近共同祖先
int max_common_len = path1.size() < path2.size() ? path1.size() : path2.size();
for(int i = 0; i < max_common_len; ++i){
if(path1[i] != path2[i])
break;
ancestor = path1[i];
}
return ancestor;
}
int main(){
node *tmp;
node *p1;
node *p2;
node *root = new node(1);
tmp = new node(2);
root->left = tmp;
tmp = new node(3);
root->right = tmp;
tmp = new node(4);
root->left->left = tmp;
tmp = new node(5);
root->left->right = tmp;
tmp = new node(6);
p1 = tmp;
root->left->left->left = tmp;
tmp = new node(7);
root->left->left->right = tmp;
tmp = new node(8);
p2 = tmp;
root->left->right->left = tmp;
tmp = new node(9);
root->left->right->right = tmp;
node *ancestor = find_lowest_common_ancestor(p1, p2, root);
cout << "ancestor: " <<ancestor->data << endl;
int ttt = 0;
return 0;
}