码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树中任意两个节点的最近公共祖先节点

时间:2017-03-11 22:16:04      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:二叉树中任意两个节点的最近公共祖先节点

1、二叉树是个搜索二叉树


2、二叉树带有指向parent的指针

    可转换成两个链表的相交节点


3、普通二叉树

保存从根节点分别到这两个节点的路径到list1和list2中

从list1和list2中找第一个不相等的节点即为最近公共祖先节点

template<class T>
BinaryTreeNode<T>*  BinaryTree<T>::lastCommnParent(BinaryTreeNode<T>*& node1, BinaryTreeNode<T>*& node2)
{
	if (_root == NULL || node1 == NULL || node2 == NULL)return NULL;
	std::list<BinaryTreeNode<T>*> list1, list2;
	GetNodePath(node1, list1);
	GetNodePath(node2, list2);
	BinaryTreeNode<T>* ret = _root;
	std::list<BinaryTreeNode<T>*>::iterator it1 = list1.begin();
	std::list<BinaryTreeNode<T>*>::iterator it2 = list2.begin();
	while (it1 != list1.end() && it2 != list2.end()){
		if (*it1 == *it2){
			ret = *it1;
			++it1, ++it2;
		}
		else
			break;
	}
	return ret;
}

template<class T>
void BinaryTree<T>::GetNodePath(BinaryTreeNode<T>*& node, std::list<BinaryTreeNode<T>*>& listpath)
{
	if (node == NULL)return;
	BinaryTreeNode<T>* cur = _root;
	BinaryTreeNode<T>* prev = cur;
	listpath.push_back(cur);
	cur = cur->_leftchild;
	while (cur != NULL || !listpath.empty()){
		while (cur != NULL){
			listpath.push_back(cur);
			if (cur == node)return;
			cur = cur->_leftchild;
			prev = cur;
		}
		BinaryTreeNode<T>* top = listpath.back();
		if (top->_rightchild == NULL || top->_rightchild == prev){
			prev = top;
			listpath.pop_back();
		}
		else
			cur = top->_rightchild;
	}
}



《完》

本文出自 “零蛋蛋” 博客,谢绝转载!

二叉树中任意两个节点的最近公共祖先节点

标签:二叉树中任意两个节点的最近公共祖先节点

原文地址:http://lingdandan.blog.51cto.com/10697032/1905402

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!