Tree

It’s a hierarchical data structure. Used to represent things like organizational hierarchy, the file system directory structure, or database indexes.

Types of trees

Traversals

Depth-first

We use a stack. Easier to implement with recursion. It preserves the shape of the tree.

flowchart TD
7 --- 23 --- 5
      23 --- 4
7 --- 3 --- 18
      3 --- 21

Pre-order

In-order

Post-order

Breadth-first

We use a queue. It does NOT preserve the shape of the tree.

flowchart TD
7 --- 23 --- 5
      23 --- 4
7 --- 8 --- 21
      8 --- 15

Given the previous tree, we would traverse in the following order: 7, 23, 8, 5, 4, 21, 15