题目:输入一颗二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。用递归和循环两种方法完成树的镜像转换。
例如输入:
8
/ \
6 10
/\ /\
5 7 9 11
输出:
8
/ \
10 6
/\ /\
11 9 7 5
定义二元查找树的结点为:
struct BSTreeNode // a node in the binary search tree (BST)
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
#include <iostream>
#include <queue>
using namespace std;
struct BSTreeNode
{
int m_Value;
BSTreeNode * m_Left;
BSTreeNode * m_Right;
BSTreeNode(int v):m_Value(v),m_Left(NULL),m_Right(NULL){}
};
class Tree
{
private:
BSTreeNode * root;
int size;
queue<BSTreeNode *> Q;
public:
BSTreeNode * getroot()
{
return this -> root;
}
Tree(){
root = NULL;
size = 0;
}
void insert(int n)
{
insertfact(n,this->root);
}
void insertfact(int n,BSTreeNode * ¤t){ // 这里 insert调用insertfact 减小接口。insertfact主要是为了递归 (* ¤t 的引用的理解
)
//即,把当前变量取一个别名,current->p_Left ==NULL 重新赋值也是可以的
if(current == NULL)
{
current = new BSTreeNode(n);
size ++;
}
else
{
if( current != NULL)
{
if(current -> m_Value > n)
{
insertfact(n, current -> m_Left );
}
else if(current -> m_Value < n)
{
insertfact(n,current->m_Right);
}
else
{
cout << "insert multi value!"<<endl;
return;
}
}
else
{
current = new BSTreeNode(n);
size ++;
}
}
}
void printlevel()
{
if(root != NULL)
Q.push(root);
while(!Q.empty())
{
BSTreeNode * now = NULL;
int level = Q.size();
while(level > 0)
{
level --;
now = Q.front();
Q.pop();
cout << now -> m_Value << " ";
if(now->m_Left != NULL)
Q.push(now->m_Left);
if(now->m_Right != NULL)
Q.push(now->m_Right);
}
cout << endl;
}
}
void MirrofXun()
{
S.push(root);
while(S.size())
{
BSTreeNode * top = S.top();
S.pop();
Swap(top->m_Left,top->m_Right);
if(top->m_Left != NULL)
S.push(top->m_Left);
if(top->m_Right != NULL)
S.push(top->m_Right);
}
}
};
int main()
{
Tree myTree;
int a[] = {8,6,10,5,7,9,11};
for(int i = 0;i < 7;i++)
{
myTree.insert(a[i]);
}
myTree.printlevel();
}
由于递归的本质是编译器生成了一个函数调用的栈,因此用循环来完成同样任务时最简单的办法就是用一个辅助栈来模拟递归。首先我们把树的头结点放入栈中。在循环中,只要栈不为空,弹出栈的栈顶结点,交换它的左右子树。如果它有左子树,把它的左子树压入栈中;如果它有右子树,把它的右子树压入栈中。这样在下次循环中就能交换它儿子结点的左右子树了。