20170928_二叉树中两个节点的最低公共祖先

20170928_二叉树中两个节点的最低公共祖先


//题目4
#include
#include
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 &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 path1, const list path2)
{
	list::const_iterator iterator1=path1.cbegin();
	list::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 path1;
	list path2;
	GetNodePath(pRoot,pNode1,path1);
	GetNodePath(pRoot,pNode2,path2);
	return GetLastCommomNode(path1,path2);
}



你可能感兴趣的:(C++基础知识专题,最低公共祖先,二叉树中两个节点的最低公共祖先)