求二叉树的镜像

思路:

采用递归的思想。对于根节点,若其左子树或右子树不为空,则互换左、右子树,然后对于左、右子树,分别递归上述处理方法,直至叶节点。
示例:
232134562

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
typedef struct TNode
{
int value;
TNode* lchild;
TNode* rchild;
}TNode,*BTree;

//采用递归进行镜像转换
void MirrorTree(BTree tree)
{
if (tree == NULL) return;
if (tree->lchild == NULL && tree->rchild == NULL) return;
TNode* temp = tree->lchild;
tree->lchild = tree->rchild;
tree->rchild = temp;
MirrorTree(tree->lchild);
MirrorTree(tree->rchild);
}