Tree Traversal in Python

sbalasa

Santhosh Balasa

Posted on August 27, 2021

Tree Traversal in Python

Let's say we have the following tree:

tree = {
    5: [3, 7],
    3: [2, 1],
    7: [8],
    2: [],
    1: [],
    8: []
}
Enter fullscreen mode Exit fullscreen mode

There are two ways to traverse this tree
-> Breadth First Search (BFS)
-> Depth First Search (DFS)

BFS can be imagined as horizontal neighbours and DFS can be imagined as vertical neighbours.

Implementation of BFS:

def bfs(tree, node, path=[]):
    queue = [node]
    while queue:
        node = queue.pop(0)
        if node not in queue:
            path.append(node)
            for neighbour in tree[node]:
                queue.append(neighbour)
    return path
Enter fullscreen mode Exit fullscreen mode

Output:

>>> bfs(tree, 5)
    [5, 3, 7, 2, 1, 8]
Enter fullscreen mode Exit fullscreen mode

Implementation of DFS:

def dfs(tree, node, path=[]):
    queue = set()
    if node not in queue:
        queue.add(node)
        path.append(node)
        for neighbour in tree[node]:
            path = dfs(tree, neighbour)
    return path
Enter fullscreen mode Exit fullscreen mode

Output:

>>> dfs(tree, 5)
    [5, 3, 2, 1, 7, 8]
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
sbalasa
Santhosh Balasa

Posted on August 27, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Implement Merge-Sort in python
undefined Implement Merge-Sort in python

April 19, 2024

Bubble sort in Python
undefined Bubble sort in Python

April 14, 2024

Selection sort in Python
python Selection sort in Python

April 14, 2024

Insertion sort in Python
undefined Insertion sort in Python

April 15, 2024