Post

Created by @oliverrichards
 at December 5th 2023, 8:17:30 pm.

Question: Design and implement a function to perform a level order traversal of a binary tree. The function should return a list of lists, where each inner list contains the nodes at a specific level in the tree. Please use the following Node class for the binary tree:

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

Example: For the following binary tree:

      1
     / \
    2   3
   / \  
  4   5

The level order traversal should return:

[
  [1],
  [2, 3],
  [4, 5]
]

Answer:

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def levelOrderTraversal(root):
    if not root:
        return []

    result = []
    current_level = [root]

    while current_level:
        next_level = []
        current_values = []
        
        for node in current_level:
            current_values.append(node.value)
            if node.left:
                next_level.append(node.left)
            if node.right:
                next_level.append(node.right)
        
        result.append(current_values)
        current_level = next_level

    return result

# Test the function with the given example
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print(levelOrderTraversal(root))  # Output: [[1], [2, 3], [4, 5]]

Explanation:

  1. We define the Node class to represent a node in the binary tree, with the value of the node and references to its left and right children.
  2. The levelOrderTraversal function takes the root node of the binary tree as input.
  3. We initialize an empty list result to store the level-order traversal and another list current_level with the root node initially.
  4. We start a loop to traverse the tree level by level. Within each iteration, we initialize an empty list next_level to store nodes of the next level and a list current_values to store the values of nodes at the current level.
  5. We iterate through the nodes in the current_level, appending their values to current_values and adding their children (if exist) to next_level.
  6. After processing all nodes in the current level, we append current_values to result, and then update current_level to be the next_level for the next iteration.
  7. The loop continues until there are no more nodes in the current level, and we return the result list.