题目描述:
操作给定的二叉树,将其变换为源二叉树的镜像。
思路:看到镜像,可能会想不起来是什么,那么就用剑指offer里面的图来解释吧,其实就是在这两个图之间放一面镜子,镜像就是镜子里面的二叉树。
上面蓝色的线表示镜子。知道了原理那么算法思路就比较好想了:使用前序遍历,每遇到一个结点,如果这个结点有子结点,那么就交换子结点,直到遍历完成。(前序遍历使用的递归实现,这里也使用递归,当然也可以使用栈来用非递归的方式实现)
代码如下:
import java.util.*;
public class Main20
{
public static void main(String[] args)
{
BinaryTreeNodes Aroot = new BinaryTreeNodes(8);
BinaryTreeNodes Aroot1 = new BinaryTreeNodes(8);
BinaryTreeNodes Aroot2 = new BinaryTreeNodes(7);
BinaryTreeNodes Aroot3 = new BinaryTreeNodes(9);
BinaryTreeNodes Aroot4 = new BinaryTreeNodes(2);
BinaryTreeNodes Aroot5 = new BinaryTreeNodes(4);
Aroot.left = Aroot1;
Aroot.right = Aroot2;
Aroot1.left = Aroot3;
Aroot1.right = Aroot4;
Aroot4.left = Aroot5;
MirrorTree(Aroot);
}
public static void MirrorTree(BinaryTreeNodes root)
{
if(root==null || (root.left==null && root.right==null))
return;
//交换子结点
BinaryTreeNodes tempTree = root.left;
root.left = root.right;
root.right = tempTree;
if(root.left!=null)
MirrorTree(root.left);
if(root.right!=null)
MirrorTree(root.right);
}
}
class BinaryTreeNodes //二叉树的节点类
{
int val;
BinaryTreeNodes left = null;
BinaryTreeNodes right = null;
public BinaryTreeNodes(int val)
{
this.val = val;
}
}
本人经验,仅供参考!