题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
题目代码
/** * @program: JavaCode * @description: 操作给定的二叉树,将其变换为源二叉树的镜像。 * 二叉树的镜像定义:源二叉树 8 / 6 10 / / 5 7 9 11 镜像二叉树 8 / 10 6 / / 11 9 7 5 * @author: Yukai Fan * @create: 2018-09-04 21:51 **/ public class MirrorTree { public static void main(String[] args) { TreeNode tree = new TreeNode(8); tree.left = new TreeNode(6); tree.left.left = new TreeNode(5); tree.left.right = new TreeNode(7); tree.right = new TreeNode(10); tree.right.left = new TreeNode(9); tree.right.right = new TreeNode(11); TreeNode mirror = Mirror(tree); System.out.println(mirror); } /* 先前序遍历这棵树的每个结点,如果遍历到的结点有子结点,就交换它的两个子节点, 当交换完所有的非叶子结点的左右子结点之后,就得到了树的镜像 */ public static TreeNode Mirror(TreeNode tree) { if (tree == null) { return null; } if (tree.left == null && tree.right == null) { return null; } TreeNode mirrorTree = tree.left; tree.left = tree.right; tree.right = mirrorTree; if (tree.left != null) { Mirror(tree.left); } if (tree.right != null) { Mirror(tree.right); } return tree; } }
/** * @program: JavaCode * @description: 创建二叉树 * @author: Yukai Fan * @create: 2018-09-04 21:52 **/ public class TreeNode { int val; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }