def levelorder(root):
if root is None:
return
mylist = [] #similar to use of queue
mylist.append(root)
while len(mylist) > 0:
print(mylist[0])
node = mylist.pop(0) #deque
if node.left is not None:
mylist.append(node.left)
if node.right is not None:
mylist.append(node.right)
This is the code i've written in python (something similar to use of queue date structure) for level order traversal but the problem here if we use mylist.pop(0), it will have time complexity of O(w) where, w is the width of the tree and in worst case if we have n nodes, it can go O(n^2). In C++, both enque and deque operation is O(1), hence we can do level order traversal in O(n) time.Can we do it O(n) in python?
EDIT: DONE