Skip to content

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.

3

4

5

7

18

21

23

Pre-order

In-order

Post-order

Breadth-first

We use a queue. It does NOT preserve the shape of the tree. Useful for nearness and pathfinding.

4

5

7

8

15

21

23

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

Deletions on a BST

1. Node with no children

No special handling required. Simply delete the node.

2. Node with one child

The node parent must now point to the child.

Initial tree

I want to delete A.

X

Y

A

B

Bl

Br

Operations

New

Delete

Delete

X

Y

B

Bl

Br

A

Resulting tree

X

Y

B

Bl

Br

3. Node with two children