1# To import queue datastructure
2import collections
3
4# Code to implement a binary tree
5class TreeNode:
6 def __init__(self, val):
7 self.val = val
8 self.left = None
9 self.right = None
10
11# Function for level Order Traversal
12def levelOrderTraversal(root):
13 ans = []
14
15 # Return Null if the tree is empty
16 if root is None:
17 return ans
18
19 # Initialize queue
20 queue = collections.deque()
21 queue.append(root)
22
23 # Iterate over the queue until it's empty
24 while queue:
25 # Check the length of queue
26 currSize = len(queue)
27 currList = []
28
29 while currSize > 0:
30 # Dequeue element
31 currNode = queue.popleft()
32 currList.append(currNode.val)
33 currSize -= 1
34
35 # Check for left child
36 if currNode.left is not None:
37 queue.append(currNode.left)
38 # Check for right child
39 if currNode.right is not None:
40 queue.append(currNode.right)
41
42 # Append the currList to answer after each iteration
43 ans.append(currList)
44
45 # Return answer list
46 return ans
47
48root = TreeNode(1)
49root.left = TreeNode(2)
50root.right = TreeNode(3)
51root.left.left = TreeNode(4)
52root.left.right = TreeNode(5)
53
54# Check if the algorithm work
55print(levelOrderTraversal(root))
56