1. Graphs
A tree is actually a type of graph, but not all graphs are trees. Simply put, a tree is a connected graph without cycles.
A graph is simply a collection of nodes with edges between (some of) them.
Representation
(1) Adjacency List
Every vertex stores a list of adjacent vertices. In an undirected graph, an edge like (a, b) store twice. once in a's adjacent vertices and once in b's adjacent vertices.
class Graph{
public Node[] nodes;
}
class Node{
public String name;
public Node[] children;
}
(2) Adjacency Matrices
An adjacency matrix is an N* N boolean matrix( where N is the number of nodes), where a true value at matrix[i][j] indicates an edge from node i to node j. (or 0s and 1s)
2. Graph Search
DFS(depth-first search): start at root, explore each branch completely before moving onto the next branch. Go deep first we go wide.
BFS(Breadth -first search): start at root, and explore each neighbor before going on to any of their children. Go wide before we go deep.
void DFS(Node root)
{
if(root == null) return;
visit(root);
root.visited = true;
foreach(Node n in root.adjacent){
if(n.visited == false){
DFS(n);
}
}
}
void BFS(Node root){
Queue queue = new Queue();
root.marked = true;
queue.enqueue(root); //add to the end of queue
while(!queue.isEmpty()){
Node r = queue.dequeue(); //remove from the front of the queue
visit(r);
foreach(Node in r.adjacent){
if(n.marked == false){
n.marked = true;
queue.enqueue(n);
}
}
}
}