## Trees and Tree Traversal

There are many different tree implementations. The following will use binary search for purposes of illustrating the various methods of traversing trees.

A **binary search tree** is a data structure that abides by the following rules:

- The left sub-tree of each node contains ONLY nodes with keys of a lesser value than the node itself
- The right sub-tree of each node contains ONLY nodes with keys of a greater value than the node itself
- Each node has at most two children or edges
- The left and right sub-trees of each node must also follow rule 1, 2, and 3
- There are no duplicate nodes

Search is O(log n) on average, but O(n) in the worst case scenario of an unbalanced tree when it then behaves similarly to a linked list.

Searching requires visiting each node a single time and can be done in different directions with different algorithms. The order determines when the value is extracted from each node. The search uses **corecursion** which starts at a base case and then builds a data set. Whereas **recursion** breaks down a data set to its base.

Two different ways to traverse the tree are:

- Depth First Search: DFS
- Breadth First Search: BFS

### Depth First Search

DFS searches typically utilize an additional stack to store data during the tree traversal. DFS uses a queue. The way that I remember it is that a BFS starts with the letter **B** and so does the work **barbeque**. The one with the “barbeque” uses a queue. The other (DFS) uses a stack.

The order in which we traverse can be:

**Preorder**: The root node is visited first before any of its children; (root, left, right)- Typically used to copy trees

**Inorder**: The root node is visited after its left tree is traversed; (left, root, right)- Usually used in a binary search
- If it is a balanced tree you will get the median value of the set in the middle of the traversal
- Will return a sorted set of values

**Postorder**: The root node is visited last; (left, right, root)- Typically used when deleting trees

The key to the order is the order in which the root node, in relation to it’s children, left and right, are visited. NOT the root of the whole tree, but each individual root branch for each pair of potential children.

Given the following tree,

```
5
/ \
3 6
/ \ \
2 4 7
```

and assuming that we will add our results to an array as we go.

Each node has the following structure (in Java).

```
public class Node {
Node left;
Node right;
int value;
boolean visited;
}
```

#### Preorder Traversal

The following is a non-recursive algorithm for traversing the tree.

- Start at the root,
**5** - Mark it as visited, add it to the stack and the result
- Result: 5
- Stack: 5

- Look at the child nodes of
**5**that have not been visited and select the least:**3** - Mark it as visited, add it to the stack and the result
- Result: 5, 3
- Stack: 5, 3

- Look at the child nodes of
**3**, that have not been visited and select the least:**2** - Mark it as visited, add it to the stack and the result
- Result: 5, 3, 2
- Stack: 5, 3, 2

- Look at the child nodes of
**2**that have not been visited and select the least: There are none so: - Pop
**2**off the stack- Stack: 5, 3

- Look at the next item on the stack:
**3** - Look at the child nodes to
**3**that have not been visited and select the least:**4** - Mark it as visited, add it to the stack and the result.
- Result: 5, 3, 2, 4
- Stack: 5, 3, 4

- Look at the child nodes of
**4**that have not been visited and select the least: There are none so: - Pop
**4**off the stack- Stack: 5, 3

- Look at the next item on the stack:
**3** - Look at the child nodes to 3 that have not been visited and select the least: There are none so:
- Pop
**3**off the stack- Stack: 5

- Look at the next item on the stack:
**5** - Look at the child nodes to
**5**that have not been visited and select the least:**6** - Mark it as visited, add it to the stack and the result.
- Result: 5, 3, 2, 4, 6
- Stack: 5, 6

- Look at the child nodes of
**6**that have not been visited and select the least:**7** - Mark it as visited, add it to the stack and the result.
- Result: 5, 3, 2, 4, 6, 7
- Stack: 5, 6, 7

- Look at the child nodes of
**7**that have not been visited and select the least: There are none so: - Pop
**7**off the stack- Stack: 5, 6

- Look at the next item on the stack:
**6** - Look at the child nodes of
**6**that have not been visited and select the least: There are none so: - Pop
**6**off the stack- Stack: 5

- Look at the next item on the stack:
**5** - Look at the child nodes of
**5**that have not been visited and select the least: There are none so: - Pop
**5**off the stack- Stack: <empty>

- Traversal is complete

Preorder result: 5, 3, 2, 4, 6, 7

#### Inorder Traversal

- Start with the root node
**5**and add it to the stack- Result:
- Stack: 5

- Look for a left node of
**5**check that it exists and that it is not visited.- Find
**3,**add it to the stack, and continue the loop - Result:
- Stack: 5, 3

- Find
- Look at the next item on the stack:
**3** - Look for a left node of
**3**, check that it exists and that it is not visited.- Find
**2,**add it to the stack, and continue the loop- Result:
- Stack: 5, 3, 2

- Find
- Look at the next item on the stack:
**2** - Look for a left node of
**2**,- There will not be a left node

- Since we are at the bottom of the left side of this part of the tree, mark
**2**as visited and add it to the result and pop it off the stack.- Result: 2
- Stack: 5, 3

- Look for a right node of
**2**, check that it exists and that it is not visited.- There will not be a right node

- Look at the next item on the stack:
**3** - Look for a left node of
**3**,- There will be a left node, but it will already be visited

- Since we have already visited the left tree of
**3**mark it as visited add it to the result and pop it off the stack- Result: 2, 3
- Stack 5

- Look for a right node of
**3**, check that it exists and that it is not visited.- Find
**4**, add it to the stack and continue the loop- Result: 2, 3
- Stack: 5, 4

- Find
- Look at the next item on the stack:
**4** - Look for a left node of
**4**,- There will not be a left node

- Since we are at the bottom of the left side of this part of the tree, mark
**4**as visited and add it to the result and pop it off the stack.- Result: 2, 3, 4
- Stack: 5

- Look at the next item on the stack:
**5** - Continue by looking at it’s left children. There will be none that are visited. So it is added to the result, popped off the stack and the process continues with the right sub-tree.

Result: 2, 3, 4, 5, 6, 7

#### Postorder Traversal

In postorder traversal the algorithm requires that we visit the left and right sub trees first, then the root node.

Result: 2, 4, 3, 7, 6, 5

### Breadth First Search

There is only one order, or kind, of breadth first search which is a level traversal.

BFS typically utilizes a queue during traversal of the tree. Given the following tree:

```
A
/ | \
B C D
/ | \
E F G
```

- Start with the root,
**A**and add it to the queue - Look at the next item in the queue,
**A**, and mark it as visited and add it to the result- Result: A
- Queue: A

- Iterate over each of it’s child nodes that have not been visited from least value to greatest value. For each
- Mark as visited, add to the result, and add to the queue
- Result: A, B, C, D
- Queue: D, C, B, A

- When there are no longer any children for
**A**remove it from the queu- Result: A, B, C, D
- Queue: D, C, B

- Return to step 2, this time, the next item in the queue will be
**B**. Continue following the steps until the queue no longer has any elements in it.

Result: A, B, C, D, E, F, G

Shortest-path BFS (queue)

DFS (stacks)

Radix sort

Dijkstra’s Algorithm

graph sorting

graph searching

## Dijkstra’s Shortest Path

public class Node {

private boolean complete; // Have we finished computing the shortest path?

private Node via; // The node from which is the current shortest path

private int distance; // The shortest distance from we we can reach this node

}

Set done;

Set fringe;

Heart of the algo is the current distance from the source to each of the destination nodes

. Start by keeping a set of each of the vertexes:

. Mark the current distance to infinity (INT_MAX) or whatever largest value as possible

. Then

. From the starting point (current node):

. Examine each connected vertex and mark the current lowest value of the distance from the current starting point to each vertex

. Store, both the lowest value and from which vertex we got that lowest value:

. Keep track of the set of vertexes that are on the fringe, a priority heap would be wonderful data structure in which to store this.

. Then remove the next closests vertex and make that our current ‘starting’ point

. When you do this, you have found the shortest path to this vertex and you can mark it as complete

. Then continue with the same algorithm, looking at each connected vertex and calculating the lowest value to get there, and from which vertex

. Once we have computed the shortest distance to all of the nodes (including the destination), we create a stack and then just follow the nodes backwards, visiting the via Node for each and push it’s id onto the stack. In the end we have a path to the destination that is the shortest.