Chapter 2 - Tree Traversal: DFS, BFS

This chapter goes over ADT, linked list and tree, but we are going to focus on tree traversal algorithm such as DFS and BFS

Understanding DFS

Preorder:

def PreOrder(root):
    if not root:
        return 
    print(root.val)
    PreOrder(root.left)
    PreOrder(root.right)

Postorder:

def PostOrder(root):
    if not root:
        return
    PostOrder(root.left)
    PostOrder(root.right)
    print(root.val)

Inorder:

The difference between these orders is how we put the print statement or how we handle operations in general. This is a good explanation of them.

Applications on DFS

Suppose we have a tree, and each node has some value, what's the max accumulated value on a path from root to leaf?


Understanding BFS

BFS does not have multiple process algorithms like DFS do because they are innately different. BFS focuses on level-order rather than reaching the deepest node. This is a simple BFS:

What this code does is that it initialize a queue, appends the root of the tree into the queue, and starts processing its children by adding them to the queue.

Last updated