This code intends to perform level order traversal for a tree. I am trying to store both level information and node element in the queue. But code gives error when I try to extract level element from the queue.
Can anyone explain why this code gives error when trying to access second element of tuple ? Is this intended usage of tuples incorrect ?
from collections import defaultdict
from queue import Queue
class Node:
def __init__(self,data):
self.val = data
self.left = None
self.right = None
def levelOrderTraversal(root):
result = defaultdict(list)
if not root:
return result
q = Queue()
level = 0
q.put((level, root))
while not q.empty():
e = q.get()
level = e[0]
#Above line throws error: TypeError: 'int' object is not subscriptable
node = e[1]
result[level].append(node.val)
if node.left:
q.put(level + 1, node.left)
if node.right:
q.put(level + 1, node.right)
return result
def test1():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
levelOrderTraversal(root)
test1()