</pre><pre name="code" class="cpp">//============================================================================
// Name : reversestring.cpp
// Author : qxyu
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<string>
#include<unordered_map>
//#include<uint32_t>
using namespace std;
/**
* Definition for a point.
*/
struct Treenode{
list<Treenode*> children;
int val;
Treenode(int x):val(x),children(NULL){}
};
bool getPath(Treenode* root, Treenode* p, list<Treenode*>& path){
if(root==p) return true;
path.push_back(root);
list<Treenode*>::iterator itr=root->children.begin();
bool found = false;
while(!found&&itr!=root->children.end()){
found = getPath(*itr,p,path);
itr++;
}
if(!found)
path.pop_back();
return found;
}
Treenode* getLastCommonNode(list<Treenode*>& path1, list<Treenode*>& path2){
if(path1.size()==0 || path2.size()==0) return NULL;
list<Treenode*>::iterator itr1 = path1.begin();
list<Treenode*>::iterator itr2 = path2.begin();
Treenode* lastNode=NULL;
while(itr1!=path1.end()&&itr2!=path2.end()){
if(*itr1==*itr2)
lastNode=*itr1;
itr1++;
itr2++;
}
return lastNode;
}
Treenode* getFirstParent(Treenode* p1, Treenode* p2, Treenode* root){
if(p1==NULL||p2==NULL||root==NULL) return NULL;
list<Treenode*> path1;
list<Treenode*> path2;
getPath(root,p1,path1);
getPath(root,p2,path2);
return getLastCommonNode(path1,path2);
}
int main()
{
Treenode* a=new Treenode(1);
Treenode* b=new Treenode(2);
Treenode* c=new Treenode(3);
Treenode* d=new Treenode(4);
Treenode* e=new Treenode(5);
Treenode* f=new Treenode(5);
Treenode* g=new Treenode(6);
Treenode* h=new Treenode(6);
Treenode* i=new Treenode(7);
a->children.push_back(b);
a->children.push_back(c);
b->children.push_back(d);
b->children.push_back(e);
c->children.push_back(f);
c->children.push_back(g);
e->children.push_back(h);
e->children.push_back(i);
Treenode* t= getFirstParent(d,h,a);
cout<<t->val;
return 0;
}
|