剑指offer第二版-27.二叉树的镜像

本系列导航:剑指offer(第二版)java实现导航帖

面试题26:二叉树的镜像

题目要求:
求一棵二叉树的镜像。

解题思路:
二叉树的镜像,即左右子树调换。从上到下,递归完成即可。

package structure;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Created by ryder on 2017/6/12.
 * 树节点
 */
public class TreeNode<T> {
    public T val;
    public TreeNode<T> left;
    public TreeNode<T> right;
    public TreeNode(T val){
        this.val = val;
        this.left = null;
        this.right = null;
    }
    //层序遍历
    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder("[");
        Queue<TreeNode<T>> queue = new LinkedList<>();
        queue.offer(this);
        TreeNode<T> temp;
        while(!queue.isEmpty()){
            temp = queue.poll();
            stringBuilder.append(temp.val);
            stringBuilder.append(",");
            if(temp.left!=null)
                queue.offer(temp.left);
            if(temp.right!=null)
                queue.offer(temp.right);
        }
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
        stringBuilder.append("]");
        return stringBuilder.toString();
    }
}
package chapter4;
import structure.TreeNode;
/**
 * Created by ryder on 2017/7/15.
 * 二叉树的镜像
 */
public class P151_MirrorOfBinaryTree {
    public static void mirrorRecursively(TreeNode<Integer> root){
        if(root==null)
            return;
        if(root.left==null&&root.right==null)
            return;
        TreeNode<Integer> temp = root.left;
        root.left = root.right;
        root.right = temp;
        mirrorRecursively(root.left);
        mirrorRecursively(root.right);
    }
    public static void main(String[] args){
        TreeNode<Integer> root = new TreeNode<>(8);
        root.left = new TreeNode<>(6);
        root.right = new TreeNode<>(10);
        root.left.left = new TreeNode<>(5);
        root.left.right = new TreeNode<>(7);
        root.right.left = new TreeNode<>(9);
        root.right.right = new TreeNode<>(11);
        System.out.println(root);
        mirrorRecursively(root);
        System.out.println(root);
    }
}

运行结果

[8,6,10,5,7,9,11]
[8,10,6,11,9,7,5]
    原文作者:ryderchan
    原文地址: https://www.jianshu.com/p/055907cc3ca1#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞