1.题目
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:
2.思路
从根节点开始,前序遍历二叉树,只要当前节点有子树,则交换左右子树位置
注意:交换子树前先判断当前节点是否为空
3.代码实现
public class BinaryTreeMirror {
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public void Mirror(TreeNode root) {
if(root==null){
return ;
}
if(root.left==null&&root.right==null){
return ;
}
TreeNode tempNode=root.left;
root.left=root.right;
root.right=tempNode;
if(root.left!=null){
Mirror(root.left);
}
if(root.right!=null){
Mirror(root.right);
}
}
//前序遍历
public void printFront(TreeNode root){
if(root==null){
return;
}
System.out.print(root.val+"\t");
printFront(root.left);
printFront(root.right);
}
//正常功能测试
@Test
public void test1() {
TreeNode treeNode1 = new TreeNode(8);
TreeNode treeNode2 = new TreeNode(6);
TreeNode treeNode3 = new TreeNode(10);
TreeNode treeNode4 = new TreeNode(5);
TreeNode treeNode5 = new TreeNode(7);
TreeNode treeNode6 = new TreeNode(9);
TreeNode treeNode7 = new TreeNode(11);
treeNode1.left = treeNode2;
treeNode1.right = treeNode3;
treeNode2.left = treeNode4;
treeNode2.right = treeNode5;
treeNode3.left = treeNode6;
treeNode3.right = treeNode7;
System.out.println("镜像前。。。。。。。。");
printFront(treeNode1);
Mirror(treeNode1);
System.out.println("镜像后。。。。。。。。");
printFront(treeNode1);
}
@Test
public void test2() {
TreeNode treeNode1 = new TreeNode(8);
TreeNode treeNode2 = new TreeNode(6);
TreeNode treeNode3 = new TreeNode(10);
TreeNode treeNode4 = new TreeNode(5);
TreeNode treeNode6 = new TreeNode(9);
treeNode1.left = treeNode2;
treeNode2.left = treeNode4;
treeNode3.left = treeNode6;
System.out.println("镜像前。。。。。。。。");
printFront(treeNode1);
Mirror(treeNode1);
System.out.println("镜像后。。。。。。。。");
printFront(treeNode1);
}
//只有一个节点
@Test
public void test3() {
TreeNode treeNode1 = new TreeNode(8);
System.out.println("镜像前。。。。。。。。");
printFront(treeNode1);
Mirror(treeNode1);
System.out.println("镜像后。。。。。。。。");
printFront(treeNode1);
}
}