Python BFS + Recursion. Reversing in recursion


  • 0

    I set up the recursion so that it recurses on the lower levels first before appending the result from the current level.

    class Solution(object):
        def reverseLevel(self, queue, rList):
            if not queue: return
            temp = []
            for i in range(len(queue)):
                node = queue.popleft()
                temp.append(node.val)
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
            self.reverseLevel(queue,rList)
            rList.append(temp)
        
        def levelOrderBottom(self, root):
            if not root: return []
            rList, queue = [], deque()
            queue.append(root)
            self.reverseLevel(queue, rList)
            return rList
    

Log in to reply
 

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