Python BFS Implementation TLE on Test Case #52 Any suggestion for optimization?


  • 0
    A

    Here is the code:

    
    
    class Solution(object):
        def longestConsecutive(self, root):
            if root == None:
                return 0
            queue = [(root,1)]
            m = 1
            def deq(q):
                x = q[0]
                del q[0]
                return x
            def enq(q,x):
                q.append(x)
                
            while (len(queue) != 0):
                (node,cur_len) = deq(queue)
                if cur_len > m:
                    m = cur_len
                if node.left != None and node.left.val == node.val + 1:
                    cur_len += 1
                    enq(queue,(node.left,cur_len))
                    cur_len -= 1
                if node.right != None and node.right.val == node.val + 1:
                    cur_len += 1
                    enq(queue,(node.right,cur_len))
                    cur_len -= 1
                if node.left != None and not node.left == node.val + 1:
                    enq(queue,(node.left,1))
                if node.right != None and not node.right == node.val + 1:
                    enq(queue,(node.right,1))
               
            return m
    

    Thx!


  • 0
    A

    Sorry. Resolved. It seems like my if-statements are not efficient.


Log in to reply
 

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