Two ways to solve this problem in Python:


  • 0

    Solution 1: Using BFS to iterate through the whole tree and keep track of the level of individual tree node for the convience of updating the answer.

    class Solution(object):
        def levelOrder(self, root):
            ans, queue = [], collections.deque()
            queue.append((1, root) )
            while queue:
                front = queue.popleft()
                if front[1]:
                    lv = front[0]
                    while len(ans) < lv:
                        ans.append([])
                    ans[lv - 1].append(front[1].val)
                    queue.append((lv + 1, front[1].left))
                    queue.append((lv + 1, front[1].right))
            return ans
    

    Solution 2: Iterate the tree in a level order:

    class Solution(object):
        def levelOrder(self, root):
            ans, q, idx = [], [[], []], 0
            q[0].append(root)
            while q[idx]:
                tmpans, q[ (idx + 1) % 2 ] = [], []
                for qi in q[idx]:
                    if qi:
                        tmpans.append(qi.val)
                        q[ (idx + 1) % 2 ].append(qi.left)
                        q[ (idx + 1) % 2 ].append(qi.right)
                if tmpans:
                    ans.append(tmpans)
                idx = (idx + 1) % 2
            return ans
    

Log in to reply
 

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