JZ27. 二叉树的镜像

33 阅读1分钟

leetcode.cn/problems/er…

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

例如输入:

     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]  

限制:

0 <= 节点个数 <= 1000

二叉树镜像定义: 对于二叉树中任意节点 root ,设其左 / 右子节点分别为 left,right ;则在二叉树的镜像中的对应 root 节点,其左 / 右子节点分别为 right,left 。

image.png

方法一:递归法

image.png

复杂度分析:

时间复杂度 O(N) : 其中 N 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N) 时间。

空间复杂度 O(N) : 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N) 大小的栈空间。

代码:

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode temp = root.left;
        root.left = mirrorTree(root.right);
        root.right = mirrorTree(temp);
        return root;
    }
}

方法二:辅助栈(或队列)

image.png

复杂度分析:

时间复杂度 O(N) : 其中 N 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N) 时间。

空间复杂度 O(N) : 如下图所示,最差情况下,栈 stack 最多同时存储 2/(N+1) 个节点,占用 O(N) 额外空间。

代码:

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) return null;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.left != null) stack.add(node.left);
            if (node.right != null) stack.add(node.right);
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }
        return root;
    }
}