Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Linked lists, trees and graphs

Tree

A tree is a data structure that consists of nodes, where each node has a value and links to its children nodes. Compared to a linked list, each node might link to many children.

1
2
5
6
3
4
7

Depth first search (DFS)

DFS goes as deep as it can along one child before it moves on to the next one.

When we visit the node before its children, it is called a pre-order traversal. When we visit the node after its children, it is called a post-order traversal.

The traversal can be implemented recursively with a function that calls itself for every child.

Pre-order traversal

1
2
5
6
3
4
7
visit 1
1 / 8

Post-order traversal

1
2
5
6
3
4
7
visit 5
1 / 8

Breadth first search (BFS)

BFS visits the tree level by level: first the root, then all its children, then all their children, and so on.

It adds each node's children to a queue, and visits the nodes from it in order, so a level is finished before the next one starts.

1
2
5
6
3
4
7
enqueue 1
1 / 12

Build it

Implement pre_order, post_order and level_order in the class below.

Build a tree
Python
# Definitions:
# class TreeNode:
# def __init__(self, val=0, children=None):
# self.val = val
# self.children = children if children is not None else []
class Tree:
def __init__(self, nested: list) -> None:
self.root = self.grow(nested)
def grow(self, nested: list | int) -> TreeNode:
if not isinstance(nested, list):
return TreeNode(nested)
node = TreeNode(nested[0])
node.children = [self.grow(child) for child in nested[1:]]
return node
def pre_order(self) -> list[int]:
# Return the values, a node before its children
return []
def post_order(self) -> list[int]:
# Return the values, a node after its children
return []
def level_order(self) -> list[int]:
# Return the values, one level at a time
return []
tree = Tree([1, [2, 5, 6], 3, [4, 7]])
print(tree.pre_order())
print(tree.post_order())
print(tree.level_order())
Was this lesson helpful?