打印二叉树的镜像——剑指offer
解题关键在于交换二叉树的左右节点
1 /** 2 public class TreeNode { 3 int val = 0; 4 TreeNode left = null; 5 TreeNode right = null; 6 7 public TreeNode(int val) { 8 this.val = val; 9 10 } 11 12 } 13 */ 14 public class Solution { 15 public void Mirror(TreeNode root) { 16 if(root == null || root.left == null && root.right == null){ 17 return; 18 } 19 TreeNode tempNode = root.left; 20 root.left = root.right; 21 root.right = tempNode; 22 if(root.left != null){ 23 Mirror(root.left); 24 } 25 if(root.right != null){ 26 Mirror(root.right); 27 } 28 } 29 }
遍历结束后相当于左右子树都交换了