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

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);
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值