# Why Graph Search and Tree Traversal Should Be Learned Together

The reason why I put these algorithms together is that they have something in common and we can save some time if we study these concepts together.

Let’s take a look at Graph first since Tree is a special type of graph. I have drawn a mindmap here. This article will focus on the following topics

# Graph Basic

• Graph categories
• Graph Representations

## Graph Categories:

A graph is a collection of nodes and edges. We can put graphs into four categories:

• Undirected and unweighted graph
• Undirected and weighted graph
• Directed and unweighted graph
• Directed and weighted graph

## Graph Representations:

There are three representation formats for Graph. Let’s have a look at it.

Vertices are stored as records or objects, and every vertex stores a list of adjacent vertices.

Using 1 and 0 to indicate if two nodes are corrected. The row represents source vertices and the column represents the destination vertices. Only the cost for one edge can be stored between each pair of vertices.

3. Incidence matrix(Boolean matrix or Edge list):

A two-dimensional boolean matrix, in which the rows represent the vertices and columns represent the edges.

# Tree Basic

## Tree Categories:

Tree is a special edition of Graph. As the tree is just a graph without a cycle.

There are two main categories of trees:

1. Unordered tree
2. Ordered tree

There are so many subcategories in the ordered tree we will not cover all of them in this article.

# Graph Search and Tree Traversal

There are two basic categories of Graph Search:

• Depth-First Search (DFS)

The main differences between BFS and DFS are:

• Data Structure: DFS make use of a stack to manage the data but BFS make use of a queue to manage the data
• Purpose: DFS is good at looking for a particular item, while BFS is good at broadly search.

## Tree Traversal (Inorder, Preorder, and Postorder)

After understanding DFS and how to implement DFS then it is easy to understand Tree Traversal.

Believe it or not, Without modifying anything your DFS code is Inorder tree traversal.

Preorder + Inorder + Postorder (Non-Recursive):

Preorder + Inorder + Postorder (Recursive):

## Commons And Differences

Graph Search:

DFS: recursive and use stack data structure. suitable for search certain target

BFS: make use of the queue to manage the state. suitable for a broad search(e.g. find the shortest path)

Tree Traversal:

Preorder: Root -> Left -> Right

Inorder: Left -> Root -> Right

Postorder: Left -> Right -> Root

As I mentioned in the first mindmap, preorder, inorder, and postorder can be treated as variations of DFS. The only differences are the order.