Stack and Queue : More Application
1. Stack and Queue are data structures used to operate data/elements in a pre-defined manner. Stack accesses to and removes the data that are latest added (i.e., the data on the top), which is called "Last in First Out" (LIFO). But Queue accesses to and removes the data that are earliest added (i.e, the data at the bottom), which is called "First In First Out"(FIFO).
2. Theoretically every recursive function can be converted to an iterative function (for loop and/or while loop). Sometimes we must use Stack as an alternative for the recursion even the stack_based function is much more complicated. For example, the recursion is naturally used for the Depth-First-Search (DFS) of a tree or binary tree (called recursive DFS). But an iterative DFS can be implemented with the Stack. It usually traverses the tree in the pre-order and uses the stack to contain and pop the nodes in the tree within a while-loop. A simple binary tree is like:
1
2 3
4 5 6 7
For the iterative DFS, the key is to add the nodes to the stack and then removes the nodes in LIFO until the stack is empty. As to the tree above, the process is like:
stack = [] ---> add 1 --->
stack = [1] ---> stack.pop() = 1: add 3, 2 --->
stack = [3, 2] ---> stack.pop() = 2: add 5, 4 --->
stack = [3, 5, 4] ---> stack.pop() = 4: nothing to do --->
stack = [3, 5] ---> stack.pop() = 5: nothing to do --->
stack = [3] ---> stack.pop() = 3: add 7, 6 --->
stack = [7, 6] ---> stack.pop() = 6: nothing to do --->
stack = [7] ---> stack.pop() = 7: nothing to do --->
stack = []
Below is an iterative DFS function used to print every root-to-leaf path of a binary tree. The core of the function is to reserve the path between current node (node) and its lower nodes (node.left or node.right) and add to the stack before the function moves downward. When a leaf is reached, the path can be printed directly because the path between the leaf and all its upper nodes are already saved to the stack.
class BinaryNode():
def __init__(self, data, left=None, right=None):
self.data = data
self.left, self.right = left, right
def print_dfs_path(bn):
stack = [bn, [bn]]
while len(stack) > 0:
path_list = stack.pop()
node = stack.pop()
if node.right is not None:
right_path_list = path_list + [node.right]
stack += [node.right] + [right_path_list]
if node.left is not None:
left_path_list = path_list + [node.left]
stack += [node.left] + [left_path_list]
if node.left is None and node.right is None:
print_path(path_list)
def print_path(path):
path_str = ''
for node in path:
path_str += '{}-->'.format(node.data)
print(path_str + '|\n')
3. Even the recursion is better than the iteration for the DFS, it's not a good choice for Breadth-First-Search (BFS) of a tree or binary tree because this kind of search is not of recursive nature. Accordingly, the queue_base iterative function is regularly used for BFS. It traverses the tree level by level and uses the queue to contain and remove the nodes in the tree within a while-loop.
For the iterative BFS, the key is to add the nodes to the queue and then removes the nodes in FIFO until the queue is empty. As to the tree above, the process is like:
queue = [] ---> add 1 --->
queue = [1] ---> queue.pop(0) = 1: add 2, 3 --->
queue = [2, 3] ---> queue.pop(0) = 2: add 4, 5 --->
queue = [3, 4, 5] ---> queue.pop(0) = 3: add 6, 7 --->
queue = [4, 5, 6, 7] ---> queue.pop(0) = 4: nothing to do --->
queue = [5, 6, 7] ---> queue.pop(0) = 5: nothing to do --->
queue = [6, 7] ---> queue.pop(0) = 6: nothing to do --->
queue = [7] ---> queue.pop(0) = 7: nothing to do --->
queue = []
Below is an iterative BFS function used to print every level of a binary tree. The core of the function is to use two queues to contain the upper/current and lower nodes separately. When the queue of upper/current nodes becomes empty, the level of lower nodes is printed out immediately before the function moves to next level.
def print_bfs_level(bn):
curr_queue, next_level = [], []
curr_queue.append(bn)
print(bn.data)
while len(curr_queue) > 0:
node = curr_queue.pop(0)
if node.left is not None:
next_level.append(node.left)
if node.right is not None:
next_level.append(node.right)
if len(curr_queue) == 0:
print_level(next_level)
curr_queue = next_level
next_level = []
def print_level(level):
level_str = ''
for node in level:
level_str += '{} '.format(node.data)
print(level_str)
End of the post
No comments:
Post a Comment