Leetcode刷题:剑指offer【面试题27 二叉树的镜像】

文章目录

  • 思路 1:递归
  • 思路 2:非递归

【面试题27 二叉树的镜像】

难度: 简单

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

Leetcode题目对应位置: 面试题27:二叉树的镜像

思路 1:递归

常规思路就是递归解法啦。(1)确定递归边界:root = null;(2)对每个 root 的操作:交换 root.left 和 root.right;(3)递归向下交换左右子树根节点即可。

时间复杂度:O(n),n 为二叉树节点数量
空间复杂度:O(n),最差情况下二叉树退化为链表,需要 O(n) 大小的调用栈空间

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root: return
        tmp = root.left
        root.left = root.right
        root.right = tmp
        self.mirrorTree(root.left)
        self.mirrorTree(root.right)
        return root

思路 2:非递归

迭代方法1: 使用栈模拟二叉树的先序遍历,并实现交换栈顶节点的左右子树。迭代的结束条件为栈空。

时间复杂度:O(n),n 为二叉树节点数量
空间复杂度:O(n),最差情况下为满二叉树,共 n 个节点,栈中最多同时存 n / 2 个节点

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root: return
        stack = [root]
        while stack:
            node = stack.pop()
            if node.left: stack.append(node.left)
            if node.right: stack.append(node.right)
            node.left, node.right = node.right, node.left
        return root

迭代方法2: 使用队列模拟二叉树的层次遍历,并实现交换队首节点的左右子树。迭代的结束条件为队列空。

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root: return
        queue = [root]
        while queue:
            node = queue.pop(0)
            if node.left: queue.append(node.left)
            if node.right: queue.append(node.right)
            node.left, node.right = node.right, node.left
        return root

你可能感兴趣的:(今天刷题了吗)