What's the difference between the data structure Tree and Graph?

后端 未结 10 1826
醉话见心
醉话见心 2021-01-29 17:35

Academically speaking, what\'s the essential difference between the data structure Tree and Graph? And how about the tree based search and Graph based search?

10条回答
  •  面向向阳花
    2021-01-29 18:08

    The other answers are useful, but they're missing the properties of each:

    Graph

    Undirected graph, image source: Wikipedia

    Directed graph, image source: Wikipedia

    • Consists of a set of vertices (or nodes) and a set of edges connecting some or all of them
    • Any edge can connect any two vertices that aren't already connected by an identical edge (in the same direction, in the case of a directed graph)
    • Doesn't have to be connected (the edges don't have to connect all vertices together): a single graph can consist of a few disconnected sets of vertices
    • Could be directed or undirected (which would apply to all edges in the graph)
      As per Wikipedia:

      For example, if the vertices represent people at a party, and there is an edge between two people if they shake hands, then this graph is undirected because any person A can shake hands with a person B only if B also shakes hands with A. In contrast, if any edge from a person A to a person B corresponds to A admiring B, then this graph is directed, because admiration is not necessarily reciprocated.

    Tree

    Image source: Wikipedia

    • A type of graph
    • Vertices are more commonly called "nodes"
    • Edges are directed and represent an "is child of" (or "is parent of") relationship
    • Each node (except the root node) has exactly one parent (and zero or more children)
    • Has exactly one "root" node (if the tree has at least one node), which is a node without a parent
    • Has to be connected
    • Is acyclic, meaning it has no cycles: "a cycle is a path [AKA sequence] of edges and vertices wherein a vertex is reachable from itself"

    There is some overlap in the above properties. Specifically, the last two properties are implied by the rest of the properties. But all of them are worth noting nonetheless.

提交回复
热议问题