一、题目描述
请完成一个函数,输入一个二叉树,该函数输出它的镜像
例如:
8 --- 二叉树A
/ \
6 10
/ \ / \
5 7 9 11
---------------------------------
8 --- 镜像二叉树
/ \
10 6
/ \ / \
11 9 7 5
二、解题思路
分析镜像二叉树的特点:根节点不变,左右孩子结点交换位置
8 8 8
/ \ 交换第一层左右孩子 / \ 交换第二层左右孩子 / \
10 6 ---> 6 10 ---> 6 10
/ \ / \ / \ / \ / \ / \
11 9 7 5 7 5 11 9 5 7 9 11
(A) (B) (C)
此时A和C就是镜像二叉树了
所以递归思路就是
1、若当前结点的左右孩子有一个存在,则交换左右孩子结点
2、若当前结点左右孩子都不存在(递归收敛条件),则return
3、若当前结点为空,则return
三、解题算法
/***************************************************************
Author:tmw
date:2018-6-30
****************************************************************/
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTreeNode
{
int data;
struct BiTreeNode* lchild;
struct BiTreeNode* rchild;
}BiTreeNode;
/**
* 求二叉树的镜像二叉树
* @param *TreeRoot
*
* 注:本代码未经测试,看逻辑就好
*/
void MirrorBiTree( BiTreeNode* TreeRoot )
{
/**边界条件**/
if( TreeRoot == NULL ) return;
/**递归收敛条件**/
if( TreeRoot->lchild == NULL && TreeRoot->rchild == NULL )
return;
/**将当前结点的左右孩子对换**/
BiTreeNode* temp = TreeRoot->lchild;
TreeRoot->lchild = TreeRoot->rchild;
TreeRoot->rchild = temp;
free(temp);
/**递归分别对左分支和右分支做相同的操作**/
if( TreeRoot->lchild )
MirrorBiTree(TreeRoot->lchild);
if( TreeRoot->rchild )
MirrorBiTree(TreeRoot->rchild);
}
梦想还是要有的,万一实现了呢~~~ヾ(◍°∇°◍)ノ゙~~~~