二元查找树的镜像:左子树的节点都大于右子树的节点。
#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
思考:二元查找树,中序遍历可以得到从小到大的递增序列;如果要得到从大到小的递减序列,我们可以先将二元查找树转换为它的镜像,然后对镜像中序遍历即可得到从大到小的递减序列。