#include <stdlib.h>
#include <iostream>
#include <queue>
using std ::cout ;
using std ::cin ;
using std ::endl;
using std ::queue ;
typedef struct BTreeNode
{
char elem;
struct BTreeNode *pleft;
struct BTreeNode *pright;
}BTreeNode;
void get_bitree_mirror(BTreeNode* proot)
{
if (proot == NULL)
return ;
BTreeNode* temp_node = proot->pleft;
proot->pleft = proot->pright;
proot->pright = temp_node;
get_bitree_mirror(proot->pleft);
get_bitree_mirror(proot->pright);
return ;
}
void get_bitree_mirror_leveltraverse(BTreeNode* proot)
{
if (proot == NULL)
return ;
queue <BTreeNode*> que;
que.push(proot);
int level_nodes_number = 0 ;
while (!que.empty())
{
level_nodes_number = que.size();
int level_count = 0 ;
while (level_count < level_nodes_number)
{
++level_count;
proot = que.front();
que.pop();
BTreeNode* temp_node = proot->pleft;
proot->pleft = proot->pright;
proot->pright = temp_node;
if (proot->pleft != NULL)
que.push(proot->pleft);
if (proot->pright != NULL)
que.push(proot->pright);
}
}
return ;
}
BTreeNode* btree_init(BTreeNode* &bt)
{
bt = NULL;
return bt;
}
void pre_crt_tree(BTreeNode* &bt)
{
char ch;
cin >> ch;
if (ch == '#' )
{
bt = NULL;
}
else
{
bt = new BTreeNode;
bt->elem = ch;
pre_crt_tree(bt->pleft);
pre_crt_tree(bt->pright);
}
}
void pre_order_traverse(BTreeNode* proot)
{
if (proot == NULL)
return ;
cout << proot->elem << " " ;
pre_order_traverse(proot->pleft);
pre_order_traverse(proot->pright);
return ;
}
int main()
{
int tree_node_number = 0 ;
BTreeNode *bt;
btree_init(bt);
pre_crt_tree(bt);
cout << "先序遍历输出如下:" << endl;
cout << "调用镜像函数前:" << endl;
pre_order_traverse(bt);
cout << endl;
get_bitree_mirror(bt);
cout << "递归调用镜像函数后:" << endl;
pre_order_traverse(bt);
cout << endl;
cout << "非递归调用镜像函数后:" << endl;
get_bitree_mirror_leveltraverse(bt);
pre_order_traverse(bt);
cout << endl;
system("pause" );
return 0 ;
}
/*
运行结果:
a b c # # # d e # # #
------以上为输入-----------
------以下为输出-----------
先序遍历输出如下:
调用镜像函数前:
a b c d e
递归调用镜像函数后:
a d e b c
非递归调用镜像函数后:
a b c d e
请按任意键继续. . .
---------------------------------
本例创建的二叉树形状:
a
b d
c e
调用递归求二叉树镜像形状:
a
d b
e c
再次调用非递归求二叉树镜像形状(即镜像的镜像):
a
b d
c e
参考资料:
http: //blog.csdn.net/beitiandijun/article/details/41958885
http: //yuncode.net/code/c_505ea04f8f6186
*/