Python simple recursive top-down (from root) and bottom-up (from leaf)


  • 0
    H

    Top down (Invert from root down):

    class Solution(object):
        def invertTree(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            if root is None:
                return
            
            root.left, root.right = root.right, root.left
            
            self.invertTree(root.left)
            self.invertTree(root.right)
            return root
    

    Bottom up (Invert from leaf up):

    class Solution(object):
        def invertTree(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            if root:
                root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
            return root
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.