二叉樹中任意兩個節點的最近公共祖先節點

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



《完》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章