N18_二叉树的镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5
package new_offer; /** * 操作给定的二叉树,将其变换为源二叉树的镜像。 * @author Sonya *思路:递归调用 */ public class N18_Mirror { public void Mirror(TreeNode root) { //TreeNode temp; if(root!=null) { TreeNode temp=null; temp=root.left; root.left=root.right; root.right=temp; if(root.left!=null) {Mirror(root.left);} if(root.right!=null) {Mirror(root.right);} } } public void print(TreeNode root) { System.out.print(root.val); if(root.left!=null) {print(root.left);} if(root.right!=null){print(root.right);} } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode t1,t2,t3,t4,t5,t6; t1=new TreeNode(1);t2=new TreeNode(2);t3=new TreeNode(3); t4=new TreeNode(4);t5=new TreeNode(5);t6=new TreeNode(6); t1.left=t2;t1.right=t3; t2.left=t4;t2.right=t5; t3.left=t3.right=null; t4.left=t6;t4.right=null; t5.left=t5.right=null; t6.left=t6.right=null; N18_Mirror n18=new N18_Mirror(); n18.print(t1); System.out.println(" "); n18.Mirror(t1); n18.print(t1); } }