找普通树的最低公共祖先

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:57   2386   0
</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;

}


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP