题目:
操作给定的二叉树,将其变换为源二叉树的镜像。
思路:
前序遍历这棵树的每个节点,如果遍历到的节点有子节点,就交换它的两个子节点。当交换完所有非叶节点的左右子节点之后,就得到了树的镜像。
过去的代码:
class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public class Solution { public void Mirror(TreeNode root) { if(root==null||(root.left==null&&root.right==null)) { return; } TreeNode temp=root.left; root.left=root.right; root.right=temp; if(root.left!=null) { Mirror(root.left); } if(root.right!=null) { Mirror(root.right); } } }
再次写的代码,带测试用例:
class TreeNode { TreeNode left; TreeNode right; int val; TreeNode(int val) { this.val=val; } } public class Solution01 { public void Mirror(TreeNode root) { if (root==null||(root.left==null&&root.right==null)) { return; } TreeNode temp=root.left; root.left=root.right; root.right=temp; Mirror(root.left); Mirror(root.right); } public static void main(String[] args) { TreeNode t1=new TreeNode(8); TreeNode t2=new TreeNode(6); TreeNode t3=new TreeNode(10); TreeNode t4=new TreeNode(5); TreeNode t5=new TreeNode(7); TreeNode t6=new TreeNode(9); TreeNode t7=new TreeNode(11); t1.left=t2; t1.right=t3; t2.left=t4; t2.right=t5; t3.left=t6; t3.right=t7; Solution01 s=new Solution01(); s.Mirror(t1); System.out.println(t1.left.right.val); } }