def _traverse_level_order_iterative(self, start_node, visit): """Traverse this binary tree with iterative level-order traversal (BFS). Start at the given node and visit each node with the given function. TODO: Running time: on each node we perform 3 operations, assumming each operations on each node take O(1) it takes 3 * O(n) for the tree to be traversed TODO: Memory usage: O(2^h) would be the worst running time if we have two children for every parent, but that might not be the case. Considering that a parent might have one child O(n) would be a better estimate.""" # TODO: Create queue to store nodes not yet traversed in level-order q = ArrayQueue() # TODO: Enqueue given starting node q.enqueue(start_node) # TODO: Loop until queue is empty while q.length() != 0: # TODO: Dequeue node at front of queue q.front() node = q.dequeue() # TODO: Visit this node's data with given function visit(node.data) # TODO: Enqueue this node's left child, if it exists if node.left: q.enqueue(node.left) # TODO: Enqueue this node's right child, if it exists if node.right: q.enqueue(node.right)
def _traverse_level_order_iterative(self, start_node, visit): """Traverse this binary tree with iterative level-order traversal (BFS). Start at the given node and visit each node with the given function. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" # TODO: Create queue to store nodes not yet traversed in level-order queue = ArrayQueue() # TODO: Enqueue given starting node queue.enqueue(start_node) # TODO: Loop until queue is empty while queue.length() != 0: # TODO: Dequeue node at front of queue node = queue.front() queue.dequeue() # TODO: Visit this node's data with given function visit(node.data) # TODO: Enqueue this node's left child, if it exists if node.left is not None: queue.enqueue(node.left) # TODO: Enqueue this node's right child, if it exists if node.right is not None: queue.enqueue(node.right)