剑指offer_二叉树---二叉树的镜像

简介: 剑指offer_二叉树---二叉树的镜像

题目描述

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

输入描述

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

解题思路

1,交换左右子树

2,递归交换左右子树的左右子节点

代码

/**
 * 
 */
package offerTest;
/**
 * <p>
 * Title:Mirror
 * </p>
 * <p>
 * Description:
 * </p>
 * 
 * @author 田茂林
 * @data 2017年8月20日 下午9:07:06
 */
public class Mirror {
    public void Mirrors(TreeNode root) {
        if (root == null || root.left == null && root.right == null){
        //为了保证代码的严谨性,这里最好加上左右子节点不能都为null
            return;
        }
        // 交换根的左右子节点
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        // 递归交换根的左右子树
        if (root.left != null)
            Mirrors(root.left);
        if (root.right != null)
            Mirrors(root.right);
    }
    public static void main(String[] args) {
    }
}


相关文章
【剑指offer】-二叉树的镜像-18/67
【剑指offer】-二叉树的镜像-18/67
|
5月前
牛客网-二叉树的镜像
牛客网-二叉树的镜像
22 0
|
11月前
剑指offer_二叉树---二叉树的下一节点
剑指offer_二叉树---二叉树的下一节点
44 0
|
11月前
剑指offer 26. 二叉树的镜像
剑指offer 26. 二叉树的镜像
24 0
|
11月前
|
算法
剑指offer_二叉树---平衡二叉树
剑指offer_二叉树---平衡二叉树
41 0
|
11月前
|
C++
剑指Offer - 面试题27:二叉树的镜像
剑指Offer - 面试题27:二叉树的镜像
46 0
|
11月前
剑指offer_二叉树---二叉树的深度
剑指offer_二叉树---二叉树的深度
50 0
|
11月前
剑指offer_二叉树---从上往下打印二叉树
剑指offer_二叉树---从上往下打印二叉树
40 0
|
11月前
剑指offer_二叉树---把二叉树打印成多行
剑指offer_二叉树---把二叉树打印成多行
45 0
|
11月前
剑指offer_二叉树---重建二叉树
剑指offer_二叉树---重建二叉树
39 0