Binary Tree Level Order Traversal

Binary Tree
Medium

Approach

Diagrams

Analysis

Time

O(n)

Space

O(n)
from collections import deque


class Solution:
    def levelOrder(self, root):
        if root is None:
            return []

        nodeValsByLevel = []
        self.levelOrderTraversal(root, nodeValsByLevel)
        return nodeValsByLevel

    def levelOrderTraversal(self, root, nodeValsByLevel):
        queue = deque([root])

        while queue:
            nodeValsCurLevel = []

            nodesInCurLevel = len(queue)

            while len(nodeValsCurLevel) < nodesInCurLevel:
                node = queue.popleft()
                nodeValsCurLevel.append(node.val)

                for child in [node.left, node.right]:
                    if child is not None:
                        queue.append(child)

            nodeValsByLevel.append(nodeValsCurLevel)

Learn

#Level Order Traversal

Videos