Clean python code


  • 1
    class Solution(object):
        def invertTree(self, root):
            if not root:
                return
    
            root.left, root.right = root.right, root.left
            map(self.invertTree, (root.left, root.right))
    
            return root

  • 0
    Q

    The code you have

    root.left, root.right = root.right, root.left
    

    looks neat, but it seems more expensive compared with the simple way of using temporary variables. You can try both submissions


  • 0

    Using temporary variables is OK. But what I'm confused with is why root.left, root.right = root.right, root.left is more expensive. Could you explain?


  • 0
    Q

    you shall try submission with both ways implementing swap and see the runtime & histogram. It seems to me that with temporary variable, the swap is faster.


  • 0

    Hi, I tried two ways several times and found that you are right.

    I also test it locally, but what makes me confused is that the result is opposed. Below is the test.

    from timeit import timeit
    
    class TreeNode(object):
        def __init__(self, value):
            self.val = value
            self.left = None
            self.right = None
    
    root = TreeNode(0)
    root.left = TreeNode(1)
    root.right = TreeNode(2)
    
    def test1():
        root.left, root.right = root.right, root.left
    
    def test2():
        tmp = root.left
        root.left = root.right
        root.right = tmp
    
    print timeit(test1, number=100000000)
    print timeit(test2, number=100000000)
    

    On my macbook pro 15,

    test1() looping 100000000 times costs about 28.5871720314 seconds

    test2() looping 100000000 times costs about 31.9967811108 seconds


  • 0
    R

    Hey I don't know how you're getting the tmp variable solution to work, but the way the pointers are working for this code, you essentially have everything pointing to itself. This will not work at all.


  • 0

    I don't understand. You mean test2?


  • 0

    In common, we swap two vars in this way

    tmp = a
    a = b
    b = tmp
    

    but in many programming language we can write like this a, b = b, a. They both work.
    In test2(), they do swap, not pointing to itself.


Log in to reply
 

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