Loading...

Trees vs Graphs

Definition

Tree:

  • A tree is a special type of graph where each node has exactly one parent, except for the root node, which has no parent.
  • Trees are hierarchical structures consisting of nodes connected by edges.
  • A tree is defined as a connected acyclic graph.

Graph:

  • A graph is a collection of nodes (vertices) and edges that connect pairs of nodes.
  • Unlike trees, graphs do not have strict hierarchical structures and can have multiple edges between nodes.
  • A graph can be either directed or undirected.

Differences

1 Hierarchical Structure:

  • Tree:
    • Trees have a hierarchical structure with a root node and multiple levels of nodes.
    • Each node in a tree has exactly one parent, except for the root node, which has no parent.
  • Graph:
    • Graphs do not have a strict hierarchical structure.
    • Nodes in a graph can have multiple parents and form arbitrary connections.

2 Connectivity:

  • Tree:
    • In a tree, every pair of nodes is connected by exactly one path.
  • Graph:
    • In a graph, nodes can be connected by multiple paths, and there can be cycles.

3 Cycles:

  • Tree:
    • Trees do not contain cycles. A cycle is a path in a graph that starts and ends at the same node.
  • Graph:
    • Graphs can contain cycles. Cyclic graphs are also known as non-tree graphs.

4 Root Node:

  • Tree:
    • Trees have a single root node from which all other nodes are descended.
  • Graph:
  • Graphs do not have a concept of a root node.

5 Edge Types:

  • Tree:
    • In a tree, each edge has a specific direction, pointing from parent nodes to child nodes.
  • Graph:
    • In a graph, edges can be directed or undirected. Directed edges have a specific direction, while undirected edges do not have a direction.

Example:

Tree:
       1
      / \
     2   3
    / \
   4   5

Graph:
       1
      / \
     2   3
    / \ / \
   4   6   7