# Breadth – first traversal only returns one node

Solution for Breadth – first traversal only returns one node
is Given Below:

I am learning about Breadth-first traversal in python. I have had a problem when writing this code.
”’

``````from collections import deque
class Tree:
def __init__(self,data):
self.data = data
self.right = None
self.left = None
def bft(root):
list_nodes = []
traversal_queue = deque([root])
while len(traversal_queue)>0:
node = traversal_queue.popleft()
list_nodes.append(node.data)
traversal_queue.append(node.left)
traversal_queue.append(node.right)
return list_nodes
n1 = Tree('A')
n2 = Tree('B')
n3 = Tree('C')
n4 = Tree('D')
n1.left = n2
n1.right = n3
n2.left = n4
print(Tree.bft(n1))
``````

The result was

``````['A']
``````

It should be [‘A’,’B’,’C’,’D’]. I don’t know why this code returned uncorrect result. Could you help me?

``````        while len(traversal_queue)>0:
node = traversal_queue.popleft()
list_nodes.append(node.data)
traversal_queue.append(node.left)
traversal_queue.append(node.right)
return list_nodes
``````

you are `return`ing `list_nodes` inside the while loop,which means it will only execute once,hence having only one value in the return list,to fix,move `return list_nodes` outside the `while` loop.

Also,you have not done a check for `None` being inserted into the queue (which will result in an `AttributeError:'NoneType' Object has no Attribute 'data'`)

Final `while` loop:

``````while len(traversal_queue)>0:
node = traversal_queue.popleft()
if node is None:
continue
list_nodes.append(node.data)
traversal_queue.append(node.left)
traversal_queue.append(node.right)
return list_nodes
``````