Which of the following statements correctly describes the key structural difference between a graph and a tree?
Think about whether cycles and connectivity are allowed in trees and graphs.
A tree is a special type of graph that is connected and has no cycles. Graphs are more general and can have cycles and may be disconnected.
Consider a graph and a tree both with 5 nodes. What is the number of edges in the tree?
int nodes = 5; int treeEdges = nodes - 1; System.out.println(treeEdges);
Remember the formula for edges in a tree with n nodes.
A tree with n nodes always has n-1 edges. So with 5 nodes, edges = 4.
Given the following adjacency list representation of a graph, what will be the output of a cycle detection algorithm?
Map<Integer, List<Integer>> graph = new HashMap<>(); graph.put(1, Arrays.asList(2)); graph.put(2, Arrays.asList(3)); graph.put(3, Arrays.asList(1)); boolean hasCycle = detectCycle(graph); System.out.println(hasCycle);
Check if the edges form a cycle in the graph.
The edges 1->2, 2->3, and 3->1 form a cycle, so the output is true.
Why does the following code fail to represent a valid tree structure?
class Node {
int val;
List children = new ArrayList<>();
}
Node root = new Node();
root.val = 1;
Node child1 = new Node();
child1.val = 2;
Node child2 = new Node();
child2.val = 3;
child1.children.add(root); // Adding root as child of child1
root.children.add(child1);
root.children.add(child2); Think about cycles and parent-child relationships in trees.
Adding root as a child of child1 creates a cycle, which is not allowed in trees.
You need to model a computer network where devices can connect to multiple others, possibly forming loops. Which data structure best represents this network?
Consider if loops and multiple connections are allowed in the network.
Graphs allow multiple connections and cycles, which fits network topology better than trees or linear structures.
