剑指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 
15 public class Solution {
16     
17     public void Mirror(TreeNode root) {
18         root=Tree(root);
19         
20     }
21     
22     public TreeNode Tree(TreeNode root){
23         if(root==null) return null;
24         if(root.left==null&&root.right==null) return root;
25         if(root.left==null) 
26         {
27             root.left=Tree(root.right);
28             root.right=null;
29             return root;
30         }
31         if(root.right==null){
32             root.right=Tree(root.left);
33             root.left=null;
34             return root;
35         }
36        TreeNode memol = root.left;
37        TreeNode memor = root.right;
38        root.left = Tree(memor);
39        root.right = Tree(memol);
40        return root;
41     }
42 }

递归二:

 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 
15 public class Solution {
16     
17     public void Mirror(TreeNode root) {
18        if(root == null) return;
19        TreeNode temp = root.left;
20        root.left = root.right;
21        root.right = temp;
22        Mirror(root.left);
23        Mirror(root.right);
24         
25     }
26     
27     
28 }

第二个方法的思想更一目了然一点

posted @ 2019-08-30 08:56  chyblogs  阅读(119)  评论(0)    收藏  举报