leetcode-Interview Question 27-Mirror of Binary Tree

 Title description:

 

 Method 1: Recursion

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

Method 2: Stack

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

 

Guess you like

Origin www.cnblogs.com/oldby/p/12747316.html