jz027.二叉树的镜像

 

题目链接

这题一种做法是递归地交换左右子节点。这个算法的时间复杂度是O(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 mirrorTree1(self, root: TreeNode) -> TreeNode:
        self.helper(root)
        return root
    
    def helper(self, root):
        if not root:
            return
        tmp = root.left
        root.left = root.right
        root.right = tmp
        self.helper(root.left)
        self.helper(root.right)

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

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