Algorithms for the main data structures, (stacks, queues, trees, linked lists, depth-first (post-order) and breadth-first traversal of trees).
2.3.1 Algorithms
Algorithms — Note 5 of 6
Candidates need to understand where stacks, queues, trees and linked lists can be used and justify their use in a scenario. Candidates need to be able to add and remove items (and search a linked list), and read, trace and write code to implement each structure, including using another structure such as a static array. Candidates need to be able to perform, and read, trace and write code for, depth-first (post-order) and breadth-first traversals of a tree.
You need to be able to read, trace and write code for the main data structures, and to perform depth-first (post-order) and breadth-first traversals of a tree. You also need to know where each structure is used.
Visit the left subtree, then the right subtree, then the node itself. Implemented recursively or with a stack.
Visit the root, then every node on the next level, left to right, level by level. Implemented with a queue.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def post_order(node):
if node is not None:
post_order(node.left) # left subtree
post_order(node.right) # right subtree
print(node.data) # then the node itself
def breadth_first(root):
queue = [root]
while len(queue) > 0:
node = queue.pop(0) # dequeue from the front
print(node.data)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right) D
/ \
B F
/ \ / \
A C E G
Post-order (left, right, node): A C B E G F D
Breadth-first (level by level): D B F A C E G