二元查找树转换为它的镜像

二元查找树的镜像:左子树的节点都大于右子树的节点。

#include <iostream>
#include <stack>
using namespace std;

struct BSTreeNode{
	int m_nValue;
	BSTreeNode* m_pLeft;
	BSTreeNode* m_pRight;
};

void InsertNode(BSTreeNode* &pRoot, int value)
{
	if(!pRoot)
	{
		pRoot=new BSTreeNode;
		pRoot->m_nValue=value;
		pRoot->m_pLeft=NULL;
		pRoot->m_pRight=NULL;
	}
	else
	{
		if(pRoot->m_nValue>value)
			InsertNode(pRoot->m_pLeft,value);
		if(pRoot->m_nValue<value)
			InsertNode(pRoot->m_pRight,value);
	}
}

void Reverse1(BSTreeNode *pRoot)//递归算法
{
	if(!pRoot)
		return;
	BSTreeNode *temp=pRoot->m_pLeft;
	pRoot->m_pLeft=pRoot->m_pRight;
	pRoot->m_pRight=temp;

	if(pRoot->m_pLeft)
		Reverse1(pRoot->m_pLeft);
	if(pRoot->m_pRight)
		Reverse1(pRoot->m_pRight);	
}

void Reverse2(BSTreeNode* pRoot)//非递归算法
{
	stack<BSTreeNode *> s;
	BSTreeNode *top;
	if(!pRoot)
		return;
	s.push(pRoot);
	while(!s.empty())
	{
		top=s.top();
		s.pop();		
		BSTreeNode* temp=top->m_pLeft;
		top->m_pLeft=top->m_pRight;
		top->m_pRight=temp;
		if(top->m_pLeft)
			s.push(top->m_pLeft);
		if(top->m_pRight)
			s.push(top->m_pRight);
	}
}

void InOrderTraverse(BSTreeNode* pRoot)//中序遍历
{
	if(pRoot)
	{		
		InOrderTraverse(pRoot->m_pLeft);
		cout<<pRoot->m_nValue<<" ";
		InOrderTraverse(pRoot->m_pRight);
	}
}

void main()
{
	BSTreeNode *pRoot=NULL;
	InsertNode(pRoot,8);
	InsertNode(pRoot,6);
	InsertNode(pRoot,10);
	InsertNode(pRoot,5);
	InsertNode(pRoot,7);
	InsertNode(pRoot,9);
	InsertNode(pRoot,11);
	InOrderTraverse(pRoot);
	cout<<endl;

	Reverse1(pRoot);
	InOrderTraverse(pRoot);
	cout<<endl;
	Reverse2(pRoot);
	InOrderTraverse(pRoot);
	cout<<endl;




}

 

具体参见:http://blog.csdn.net/v_JULY_v

思考:二元查找树,中序遍历可以得到从小到大的递增序列;如果要得到从大到小的递减序列,我们可以先将二元查找树转换为它的镜像,然后对镜像中序遍历即可得到从大到小的递减序列。

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值