Level Order Traversal of Binary Tree

editor-page-cover

Problem Statement

Given the root of a binary tree, display the node values at each level. Node values for all levels should be displayed on separate lines. Let’s take a look at the below binary tree.

widget

Level order traversal for this tree should look like: 100; 50, 200; 25, 75, 350


Hint

  • Breadth first traversal

Try it yourself

def level_order_traversal(root):
result = ""
#TODO: Write - Your - Code
return result

Solution

from collections import deque
def level_order_traversal(root):
result = []
if not root:
result = "None"
return result
queue = deque()
queue.append(root)
while queue:
level_size = len(queue)
level_nodes = []
for _ in range(level_size):
temp = queue.popleft()
level_nodes.append(str(temp.data))
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
result.append(", ".join(level_nodes))
return "; ".join(result)
arr = [100,50,200,25,75,350]
root = create_BST(arr)
print("InOrder Traversal:", end = "")
display_inorder(root)
print("\nLevel Order Traversal: ", level_order_traversal(root))

Solution Explanation

Runtime Complexity

The runtime complexity of this solution is linear, O(n)O(n).

Memory Complexity

The memory complexity of this solution is linear, O(n)O(n).


Solution Breakdown

  1. Initialize a queue, queue, with the root node.

  2. Iterate over the queue until it’s empty:

    • For each level, calculate the size (level_size) of the queue.
    • Initialize an empty list level_nodes.
    • Iterate level_size times:
      • Dequeue a node from the queue.
      • Append the value of the dequeued node in level_nodes.
      • Enqueue the left child and the right child of the dequeued node in queue, if they exist.
    • Convert level_nodes to a comma-separated string and store it in result.
  3. Return the result.

Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!