剑指 Offer 27. 二叉树的镜像

剑指 Offer 27. 二叉树的镜像

题目介绍:请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:

4
/
2 7
/ \ /
1 3 6 9
镜像输出:

4
/
7 2
/ \ /
9 6 3 1

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

思路主要两个,第一个是递归的思想,第二个是辅助栈的思想。

一、递归

递归的思想是自下而上的进行交换。

class Solution {
        public TreeNode mirrorTree(TreeNode root) {
            if (root == null) return null;
            //设置一个tmp,暂存root.left(左节点)的值
            TreeNode tmp = root.left;
            //递归root.right(右节点)的值,并将返回值放到root.left(左节点)的值
            root.left = mirrorTree(root.right);
            //递归root.left(左节点)的值,并将返回值放到root.right(右节点)的值
            root.right = mirrorTree(tmp);
            return root;
        }
    }

上面写的有点简洁,是借鉴了K神的代码,如果复杂点的话,代码如下:

class Solution {
   public TreeNode mirrorTree(TreeNode root) {
       if (root == null) return null;
       //其实就是把左右节点进行相互交换,然后再递归即可
       TreeNode tmp = root.left;
       root.left = root.right;
       root.right = tmp;
       mirrorTree(root.left);
       mirrorTree(root.right);
       return root;
   }
}

二、辅助栈

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) return null;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.add(root);
        while (!stack.isEmpty()) {
        /*循环交换:当stack为空时跳出
        1.把出栈设置为node
        2.添加子节点,将左、右节点入栈
        3.然后node的左、右节点进行交换
        */
            TreeNode node = stack.pop();
            if (node.left != null) stack.add(node.left);
            if (node.right != null) stack.add(node.right);
            
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        //返回根节点root
        return root;
    }
}
posted @ 2021-07-31 19:34  RainsX  阅读(41)  评论(0)    收藏  举报