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:
Node
class to represent a node in the binary tree, with the value of the node and references to its left and right children.levelOrderTraversal
function takes the root node of the binary tree as input.result
to store the level-order traversal and another list current_level
with the root node initially.next_level
to store nodes of the next level and a list current_values
to store the values of nodes at the current level.current_level
, appending their values to current_values
and adding their children (if exist) to next_level
.current_values
to result
, and then update current_level
to be the next_level
for the next iteration.result
list.