4 Line Python Solution (52 ms)


  • 6
    M
    def invertTree(self, root):
        if root is None:
            return None
        root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
        return root

  • 0
    C

    It seems we can complete it in 3 lines:

    def invertTree1(self, root):
        if root:
            root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
            return root

  • 0
    S

    Why I always get error after change it like the following code?
    if root:

            root.left = self.invertTree(root.right)
            root.right = self.invertTree(root.left)
    
            return root

  • 1
    C

    The reason is simple, in python you can exchange two variables "in place", such as if you want to change a, b, then you can do a, b = b, a. But if you want to do in seperate lines, like C/C++, etc, you should create a temporary variable, like int tmp = a; a = b; b = tmp, so you should change your code as:
    tmp = root.left root.left = self.invertTree(root.right) root.right = self.invertTree(tmp)


  • 0
    S

    Thanks for your help! I just learn python, it is fun!


Log in to reply
 

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