剑指Offer第十一题:二叉树的镜像
问题描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5
问题分析
由分析可知,所谓的二叉树镜像就是将二叉树的所有左子树变成右子树,右子树变成左子树。
算法分析
- 我们需要两个循环,第一个循环将原二叉树的根节点的左右子树调换后,继续讲左子树的所有子树做相同操作。另外一个循环对根节点的右子树做相应的操作
源代码
1 public class TreeNode { 2 int val = 0; 3 TreeNode left = null; 4 TreeNode right = null; 5 6 public TreeNode(int val) { 7 this.val = val; 8 9 } 10 11 } 12 13 public class Solution { 14 public void Mirror(TreeNode root) { 15 TreeNode node=root; 16 TreeNode temp=new TreeNode(0); 17 18 while(node!=null) { 19 temp=node.left; 20 node.left=node.right; 21 node.right=temp; 22 node=node.left; 23 } 24 while(root!=null&&root.right!=null) { 25 root=root.right; 26 temp=root.left; 27 root.left=root.right; 28 root.right=temp; 29 } 30 } 31 }