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

题目:

思路:

1、很明显递归处理,交换当前节点的左右子树,然后递归处理其左子树和右子树
2、也可以通过栈深度优先的去交换,或者通过队列广度优先的去交换(一层层的交换)

代码:

Python

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

class Solution(object):
    def mirrorTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root is None:
            return None
        # # result = root不行, 执行到root.left时root.left=result.left=root.right
        # result = TreeNode(root.val)
        # result.left = self.mirrorTree(root.right)
        # result.right = self.mirrorTree(root.left)
        # return result

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

class Solution(object):
    def mirrorTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root is None:
            return None
        # 通过队列实现
        queue = [root]
        while queue:
            node = queue.pop()
            if node.left: queue.append(node.left)
            if node.right: queue.append(node.right)
            node.left, node.right = node.right, node.left
        return root

相关问题

posted @ 2020-06-03 18:30  一只背影  阅读(150)  评论(0编辑  收藏  举报