class TestArrayQueue(unittest.TestCase): def setUp(self): self.queue = ArrayQueue() def test_enqueue(self): self.queue.enqueue(1) self.queue.enqueue(2) self.queue.enqueue(3) self.assertEqual(self.queue.size, 3) def test_dequeue(self): self.queue.enqueue(1) self.queue.enqueue(2) self.assertEqual(self.queue.dequeue(), 1) def test_peek(self): self.queue.enqueue(1) self.assertEqual(self.queue.peek(), 1) def test_peek_when_stack_is_empty(self): with self.assertRaises(Exception): self.queue.peek() def test_is_empty_when_stack_is_empty(self): self.assertEqual(self.queue.is_empty(), True) def test_is_empty_when_stack_is_not_empty(self): self.queue.enqueue(1) self.assertEqual(self.queue.is_empty(), False) def test_show_all(self): self.queue.show_all()
def breadthfirst(self): if not self.is_empty(): fringe = ArrayQueue() fringe.enqueue(self.root()) while not fringe.is_empty(): p = fringe.dequeue() yield p for child in self.children(p): fringe.enqueue(child)
def BFS(G, a): status={} for node in G.nodes(): status[node]='U' nodes=ArrayQueue() nodes.enqueue(a) status[a]='V' while nodes.is_empty()==False: pnode=nodes.dequeue() for node in G.neighbors(pnode): if status[node]=='U': nodes.enqueue(node) status[node]='V' status[pnode]='P' print(pnode) return
def items_level_order(self): """Return a list of all items in this binary search tree found using level-order traversal""" # Create a queue to store nodes not yet traversed in level-order queue = ArrayQueue() # Create an items list items = list() # Enqueue the root node if this tree is not empty if self.is_empty() is False: queue.enqueue(self.root) # Loop until the queue is empty while queue.is_empty() is False: # Dequeue the node at the front of the queue node = queue.dequeue() # Add this node's data to the items list items.append(node.data) # Enqueue this node's left child if it exists if node.left is not None: queue.enqueue(node.left) # Enqueue this node's right child if it exists if node.right is not None: queue.enqueue(node.right) # Return the items list return items