二叉树的镜像

题目描述

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

输入描述:

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

思路:递归思想,从这个图来看,第一层就一个元素所以交换不了;第二层有两个左右子树,所以可以交换;第三层,有四个叶子结点,那我们可以这样想,分为左右两个大块,这两个大块有有左右两个小块,于是我们先交换左边的5、7
在右边的9、11,最后我们把左右两个整体一起交换,就得到了11、9、7、5(可能是瞎说的我自己的理解吧)。

public class Solution {
public void Mirror(TreeNode root) {
if(root == null){
return;
}
if(root.left == null && root.right == null){
return;
}
TreeNode tmp = null;

//交换左右子树
tmp = root.left;
root.left = root.right ;
root.right = tmp;

if(root.left != null){
Mirror(root.left); //传说中的递归
}
if(root.right != null){
Mirror(root.right);
}
}
}

 

 

posted @ 2019-07-15 21:52  WhyNott  阅读(131)  评论(0编辑  收藏  举报