DEV Community

Cover image for Graph and Trees - Basic
Debjoty Mitra
Debjoty Mitra

Posted on

Graph and Trees - Basic

Graph

A graph is a non-linear data structure composed of nodes and edges. The nodes are also known as vertices; edges are lines or arcs connecting any two nodes in the graph. There are two types of representation techniques for a graph. Those are:

  • Matrix: Even though we won't be using it frequently, it's still helpful to have some familiarity with it.
  • List:
    • Arrays of Vectors
    • Vectors of Vectors

Vertices and Edges

Graph

This is a graph with five Vertices. We can also call them Nodes. If we connect the vertices with lines, then the lines will be called Edges.

Graph

Basically, all the edges above are bidirectional. It means that we can go from 1 to 3 and also from 3 to 1. We can make an edge unidirectional by giving it a detection using an arrow.

Graph

Tree

A tree is a graph that has no cycles in it.

Graph

This is not a tree because there is a cycle between 1, 2, and 3. If we remove that edge, then it will become a tree.

Graph

If a tree has n nodes, then the number of edges it will have is n-1.

Top comments (1)

Collapse
 
suyious profile image
Suyash K.

love the diagrams ❤️