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

 

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。 
输入描述:
二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

 

思路:

先前序遍历这棵树的每个结点,如果遍历到的结点有子结点,就交换它的两个子节点,
当交换完所有的非叶子结点的左右子结点之后,就得到了树的镜像
 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) return;
17         if(root.left==null&&root.right==null) return;
18         TreeNode temp=root.left;
19         root.left=root.right;
20         root.right=temp;
21         Mirror(root.left);
22         Mirror(root.right);
23     }
24 }

 

 1 public class Solution {
 2     public void Mirror(TreeNode root) {
 3         if(root == null)
 4             return;
 5         if(root.left == null && root.right == null)
 6             return;
 7          
 8         TreeNode pTemp = root.left;
 9         root.left = root.right;
10         root.right = pTemp;
11          
12         if(root.left != null)
13             Mirror(root.left);
14         if(root.right != null)
15             Mirror(root.right);
16     }
17 }

 

posted on 2017-06-26 17:03  olive_gyr  阅读(161)  评论(0编辑  收藏  举报