Representations

A graph is similar to a tree, but it has no root node. This distinction means it can be used to model all sorts of different types of data - social networks, for example.

This also means that there might be cycles - similar to a Linked List, or disconnectivity where one node is orphaned.

Graphs can be trees. For a graph to be a valid tree, it must have exactly n - 1 edges, where n is the number of nodes.

Any less, and it can’t possibly be fully connected. Any more, and it has to contain cycles. Additionally, if the graph is fully connected and contains exactly n - 1 edges, it can’t possibly contain a cycle, and therefore must be a tree!

Graphs can be represented in 3 ways:

OperationAdjacency MatrixAdjancency List
Storage spaceBecause of the use of a matrix, space =
+ vertexStorage must increase to , and to achieve this we must copy the entire array. Therefore, , as we’re just adding an item to a list
+ edgematrix[i][j] = 1, so Same as adding a vertex,
- vertexStorage must be decreased, so To remove a vertex, we must search for it. After this we must search for edges, so
- edgematrix[i][j] = 0, so Must traverse through all edges, so
QueryingContent of the matrix must be checked - this lookup is To check for an edge, we must check for vertices adjacent to a given vertex. A vertex can have neighbours and worst-case we have to check every one. So time complexity is .