剑指offer18题

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }
}

/**
 * 操作给定的二叉树,将其变换为源二叉树的镜像。
 * 思路:
 * 1、逐层深入,把左右两边交换
 *
 * code:
 */

public class Solution18 {
    public void Mirror(TreeNode root) {
        if (root == null) {
            return;
        }
        exchange(root);
    }

    private void exchange(TreeNode root) {
        doExchange(root);
        if (root.left != null) {
            exchange(root.left);
        }
        if (root.right != null) {
            exchange(root.right);
        }
    }

    private void doExchange(TreeNode root) {
        if (root == null) {
            return;
        }
        TreeNode temp;
        temp = root.left;
        root.left = root.right;
        root.right = temp;
    }

}

 

posted @ 2020-08-09 20:45  Adom_ye  阅读(105)  评论(0编辑  收藏  举报