Hello everyone,
I've been working on implementing level order traversal in my code, following the article. However, I'm facing some difficulties and would appreciate some assistance.
Here's my code implementation so far
Code:
from collections import deque
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def levelOrderTraversal(root):
if root is None:
return []
result = []
queue = deque()
queue.append(root)
while queue:
level_size = len(queue)
current_level = []
for _ in range(level_size):
current_node = queue.popleft()
current_level.append(current_node.val)
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
result.append(current_level)
return result
# Example usage
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(levelOrderTraversal(root))
The problem I'm facing is that when I run this code, I'm not getting the expected output. It seems like the level order traversal is not working correctly. I've reviewed the code multiple times and compared it to the algorithm described in the blog post, but I couldn't identify the issue.
Could someone please take a look at the code and point out any potential mistakes or suggest improvements? I'm open to any suggestions or alternative implementations that could help me resolve this problem.