Python recursive solution: beats 92%


  • 2
    S
    class Solution(object):
        def invertTree(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            if root == None:
                return None 
            
            def invert(root):
                
                if not root.left and not root.right:
                    return root
                left = root.left
                right = root.right
                root.left = invert(right) if right else None
                root.right = invert(left) if left else None
                
                return root
            
            return invert(root)

  • 0
    A
    class Solution(object):
       def invertTree(self, root):
          if (root == None):
             return 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.