Looking for optimization in Python


  • 0
    S

    Python solution but slow, looking for improvement

    '''
    import Queue
    class Solution(object):
    def verticalOrder(self, root):

        if(root == None):
            return []
        nodeQueue = Queue.Queue()
        columnQueue = Queue.Queue()
        resDic = {}
        nodeQueue.put(root)
        columnQueue.put(0)
        minium = 0
        maxium = 0
        results = []
        while(nodeQueue.empty() == False):
            currentNode = nodeQueue.get()
            currentColumn = columnQueue.get()
            if(resDic.has_key(currentColumn) == False):
                resDic[currentColumn] = []
            resDic[currentColumn].append(currentNode.val)
            if(currentNode.left != None):
                nodeQueue.put(currentNode.left)
                columnQueue.put(currentColumn - 1)
                minium = min(minium, currentColumn - 1)
            if(currentNode.right != None):
                nodeQueue.put(currentNode.right)
                columnQueue.put(currentColumn + 1)
                maxium = max(maxium, currentColumn + 1)
        for x in range(minium, maxium + 1):
            results.append(resDic[x])
        return results
    

    '''
    The runtime is 66ms, I think it's probably because the Queue, any idea about what is the lowest cost data structures in this algorithms. The algorithms is from yainci's java solution. It's pretty clean. I'm also curious why the runtime of java and python has such a huge difference by using similar algorithms. Thanks advance for any advice


Log in to reply
 

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