https://blog.csdn.net/u010425776/article/details/50886193
分析:所谓“镜像”就是从镜子里看到的样子。我们可以画一棵二叉树,然后画出该二叉树的镜像。画完图之后我们会发现,所谓“二叉树的镜像”就是把二叉树中所有子树的左孩子和右孩子进行交换。因此需要遍历二叉树所有的结点,在遍历的同时交换非叶子结点的左右子树。遍历我们可以使用先序遍历,首先判断当前根结点是否为叶子结点,若非叶子结点,则交换左右孩子,然后再分别对左右孩子进行相同的操作。
首先,我们需要构造二叉树的结点类,一个结点中包含一个数据域data、一个左孩子left、一个右孩子right,代码如下:
-
/**
-
* 二叉树的结点
-
*/
-
class BinaryTreeNode<T>{
-
T data;//结点的数据域
-
BinaryTreeNode<T> left;//左子树
-
BinaryTreeNode<T> right;//右子树
-
}
下面开始编写镜像函数:
-
/**
-
* 二叉树镜像函数
-
* @param root 输入二叉树的根结点
-
*/
-
public static <T> void binaryTreeMirror(BinaryTreeNode<T> root){
-
//若二叉树为空
-
if(root==null)
-
return;
-
//若二叉树只有一个结点
-
if(root.left==null && root.right==null)
-
return;
-
//若二叉树为有孩子结点,则交换左右子树
-
{
-
//交换左右子树
-
BinaryTreeNode<T> temp = root.left;
-
root.left = root.right;
-
root.right = temp;
-
}
-
//分别对左右重复上述操作
-
{
-
if(root.left!=null)
-
binaryTreeMirror(root.left);
-
if(root.right!=null)
-
binaryTreeMirror(root.right);
-
}
-
}
为了能够对上述算法进行测试,我编写了一个二叉树的中序遍历函数,我们可以比较二叉树镜像前和镜像后的中序遍历结果来判断算法是否正确。二叉树中序遍历函数如下:
-
<span style="white-space:pre"> </span>/**
-
* 二叉树的中序遍历
-
* @param root 输入的二叉树的根
-
*/
-
public static <T> void preOrder(BinaryTreeNode<T> root){
-
//若当前二叉树为空
-
if(root==null)
-
return;
-
//中序遍历二叉树
-
{
-
preOrder(root.left);//中序遍历左子树
-
System.out.print(root.data+",");//访问根结点
-
preOrder(root.right);//中序遍历右子树
-
}
-
}
一切准备工作就绪,下面就开始测试我们的算法吧。
我创建了一棵四个结点的二叉树,并且所有结点均是左孩子。那么经过镜像后该二叉树的所有结点应该都是右孩子。并且前后两棵树的中序遍历正好是逆序关系。
-
public static void main(String[] args){
-
BinaryTreeNode<Integer> root = new BinaryTreeNode<Integer>();
-
BinaryTreeNode<Integer> root1 = new BinaryTreeNode<Integer>();
-
BinaryTreeNode<Integer> root2 = new BinaryTreeNode<Integer>();
-
BinaryTreeNode<Integer> root3 = new BinaryTreeNode<Integer>();
-
root.data = 0;
-
root1.data = 1;
-
root2.data = 2;
-
root3.data = 3;
-
root.left = root1;
-
root1.left = root2;
-
root2.left = root3;
-
System.out.println("镜像前:");
-
preOrder(root);
-
System.out.println("镜像后:");
-
binaryTreeMirror(root);
-
preOrder(root);
-
}
输出结果为:
镜像前:3,2,1,0
镜像后:0,1,2,3