16-line iterative python solution using queue


  • 0
    def verticalOrder(self, root):
        neg,pos = [], []                 #store the negative and positive vertical_lev node values
        q = collections.deque([(root,0)])
        while q:
            curr, lev = q.popleft()      #lev is the vertical lev
            if curr is None: continue
            if lev>=0:
                if lev>=len(pos): pos.append([])
                pos[lev].append(curr.val)
            else: 
                i = -lev-1
                if i>=len(neg): neg.append([])
                neg[i].append(curr.val)
            q.append((curr.left,lev-1))
            q.append((curr.right, lev+1))
    
        return neg[::-1]+pos

Log in to reply
 

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