Binary Tree Level Order Traversal

1 minute read

Level Order Traversal

Question

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

Example:

Input:{1,2,3}
Output:[[1],[2,3]]
Explanation:
  1
 / \
2   3
it will be serialized {1,2,3}
level order traversal


Input:{1,#,2,3}
Output:[[1],[2],[3]]
Explanation:
1
 \
  2
 /
3
it will be serialized {1,#,2,3}
level order traversal

Analyzation

Queue

Challenge 1: Using only 1 queue to implement it.

Challenge 2: Use BFS algorithm to do it.

IMPORTANT PATTERN!!

All binary tree problem that relates to “LEVEL” or “DEPTH” can use this pattern.

Import a deque package and use the queue structure. (Only 1 queue & BFS algorithm) See the code below.

The Code

from collections import deque
class Solution:
    """
    @param root: A Tree
    @return: Level order a list of lists of integer
    """
    def levelOrder(self, root):
        # write your code here
        if root is None:
            return []
            
        queue = deque([root])
        result = []
        
        # while queue is not empty
        while queue:
            level = []
            for _ in range(len(queue)):
                node = queue.popleft() # get the first node of the queue
                level.append(node.val)
                
                # add children of the node to queue
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                    
            # put the same level nodes in a list
            result.append(level)
        
        return result

Time & Space Complexity

  • Time complexity: O(n). Remember that the best case of a Binary Tree is O(logn) since it is a balanced tree but the worst case is O(n) because it can skew to only one side.
  • Space complexity: O(n). Remember that the space complexity is always about how many nodes there are in a Binary Tree. If the tree is well-balanced then it is O(logn) but the worst case will be O(n).