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

在这里插入图片描述

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

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

    def mirrorTree_stack(self, root: TreeNode) -> TreeNode:
        """
        使用栈,先序遍历。
        
        二叉树的先序、中序、后序类似于图的深度遍历,非递归算法对需要使用栈
        :param root:
        :return:
        """
        from collections import deque

        stack = deque()
        p = root
        while p or stack:
            if p:
                p.left, p.right = p.right, p.left
                stack.append(p)
                p = p.left
            else:
                p = stack.pop()
                p = p.right
        return root

    def mirrorTree_queue(self, root: TreeNode) -> TreeNode:
        """
        使用队列,层次遍历。
        
        二叉树的层次遍历类似于图的广度遍历
        :param root: 
        :return: 
        """
        if not root:
            return root
        from collections import deque

        queue = deque()
        p = root
        queue.append(p)
        while queue:
            p = queue.popleft()
            p.left, p.right = p.right, p.left
            if p.left:
                queue.append(p.left)
            if p.right:
                queue.append(p.right)
        return root

[题目来源于leetcode剑指offer]

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页