0

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?

jacobdavis
  • 35
  • 6

1 Answers1

0
        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 returning 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 
xkcdjerry
  • 965
  • 4
  • 15
  • Thanks a lot for your advances. However, I think that break is easier to undenstand when using continue. `if node is None: break` – jacobdavis Aug 03 '21 at 02:11
  • 1
    the problem with `break` is that it leaves the loop behind completely, which means any nodes left in `traversal_queue` is unprocessed. You can use `if node is not None:(the three processing statements)` if you don't feel comfortable using `continue` :-) – xkcdjerry Aug 03 '21 at 07:52