A tree is a non-linear data structure that represents the hierarchy. A tree is a collection of nodes that are linked together to form a hierarchy. A graph is like a tree data structure is a collection of objects or entities known as nodes that are connected to each other through a set of edges. A tree follows some rule that determines the relationship between the nodes, whereas graph does not follow any rule that defines the relationship among the nodes. A graph contains a set of edges and nodes, and edges can connect the nodes in any possible way.
Differences between Tree and Graph are stated below
Basis for comparison | Tree | Graph |
---|---|---|
Definition | Tree is a non-linear data structure in which elements are arranged in multiple levels. | A Graph is also a non-linear data structure. |
Structure | It is a collection of edges and nodes. For example, node is represented by N and edge is represented as E, so it can be written as: T = {N,E} | It is a collection of vertices and edges. For example, vertices are represented by V, and edge is represented as ‘E’, so it can be written as: T = {V, E} |
Root node | In tree data structure, there is a unique node known as a parent node. It represents the topmost node in the tree data structure. | In graph data structure, there is no unique node. |
Loop formation | It does not create any loop or cycle. | In graph, loop or cycle can be formed. |
Model type | It is a hierarchical model because nodes are arranged in multiple level, and that creates a hierarchy. For example, any organization will have a hierarchical model. | It is a network model. For example, facebook is a social network that uses the graph data structure. |
Edges | If there are n nodes then there would be n-1 number of edges. | The number of edges depends on the graph. |
Type of edge | Tree data structure will always have directed edges. | In graph data structure, all the edges can either be directed edges, undirected edges, or both. |
Applications | It is used for inserting, deleting or searching any element in tree. | It is mainly used for finding the shortest path in the network. |