Could anyone give a clear and concise explanation for when you use graphs vs when to use trees for data structures?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
Trees are Graphs.
They are specifically directed, acyclic graphs where all child nodes only have one parent. If you need more than one parent then you use a DAG. If you need cycles or the graph needs to be undirected you'd use some kind of graph implementation. Note that the time and space complexity increases dramatically once you move into full graphs.
You can use graphs and trees for both modeling a problem and solving a problem, but sometimes you can convert a graph to a tree by clipping connections to make the problem easier to solve.
Since you ask for simple examples I will give an example for modeling. If you were to model roads you would use a graph since roads can form a circuit, and thus you need a graph. If you were to model a river and its branches, you would use a tree since rivers don't flow in circles. Once could argue that you need a directed acyclic graph for rivers because they have islands, but this is just a simple example.