20170928_二叉树中两个节点的最低公共祖先
//题目4
#include<iostream>
#include<list>
using namespace std;
struct BiTree
{
int value;
BiTree *pLeft;
BiTree *pRight;
BiTree(int x):value(x),pLeft(nullptr),pRight(nullptr) {}
};
//得到指定节点的路径
bool GetNodePath(BiTree *pRoot, BiTree *pNode, list<BiTree *> &path)
{
if(pRoot==nullptr || pNode==nullptr)
return false;
path.push_back(pRoot);
bool found=false;
if(pRoot==pNode)
{
found=true;
return found;
}
if(!found && pRoot->pLeft)
found=GetNodePath(pRoot->pLeft,pNode,path);
if(!found && pRoot->pRight)
found=GetNodePath(pRoot->pRight,pNode,path);
if(!found)
path.pop_back();
return found;
}
//得到两条路径的最后公共节点
BiTree *GetLastCommomNode(const list<BiTree *> path1, const list<BiTree *> path2)
{
list<BiTree *>::const_iterator iterator1=path1.cbegin();
list<BiTree *>::const_iterator iterator2=path2.cbegin();
BiTree *pLast=nullptr;
while(iterator1 != path1.cend() && iterator2 != path2.cend())
{
if(iterator1 == iterator2)
pLast=*iterator1;
++iterator1;
++iterator2;
}
}
//综合起来的函数
BiTree *GetLastCommomNodeParent(BiTree *pRoot, BiTree *pNode1, BiTree *pNode2)
{
if(pRoot==nullptr || pNode1==nullptr || pNode2==nullptr)
return nullptr;
list<BiTree *> path1;
list<BiTree *> path2;
GetNodePath(pRoot,pNode1,path1);
GetNodePath(pRoot,pNode2,path2);
return GetLastCommomNode(path1,path2);
}