Fork me on GitHub

二叉树的镜像

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述:

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5
 1 /*
 2  * 题目描述
 3  * 操作给定的二叉树,将其变换为源二叉树的镜像。
 4  * 输入描述:
 5  * 二叉树的镜像定义:
 6  * 源二叉树 
 7             8
 8            /  \
 9           6   10
10          / \  / \
11         5  7 9 11
12  * 镜像二叉树
13             8
14            /  \
15           10   6
16          / \  / \
17         11 9 7  5
18  */
19 
20 public class Main18 {
21 
22     public static void main(String[] args) {
23         
24     }
25     
26     public class TreeNode {
27         int val = 0;
28         TreeNode left = null;
29         TreeNode right = null;
30 
31         public TreeNode(int val) {
32             this.val = val;
33         }
34     }
35     
36     public void Mirror(TreeNode root) {
37         if (root == null) {
38             return;
39         }
40         if (root.left == null && root.right == null) {
41             return;
42         }
43         
44         TreeNode temp = null;
45         temp = root.left;
46         root.left = root.right;
47         root.right = temp;
48         
49         if (root.left != null) {
50             Mirror(root.left);
51         }
52         if (root.right != null) {
53             Mirror(root.right);
54         }
55     }
56 }

 

posted @ 2019-07-01 14:51  gentleKay  阅读(111)  评论(0编辑  收藏  举报