Which of the following is a key reason why trees cannot model certain relationships that graphs can?
Think about whether trees can have loops or repeated connections.
Trees are hierarchical and acyclic, so they cannot represent cycles. Graphs can represent cycles and more complex relationships.
What is the output of the following JavaScript code that creates a graph with a cycle and prints its adjacency list?
const graph = {
A: ['B'],
B: ['C'],
C: ['A']
};
for (const node in graph) {
console.log(node + ' -> ' + graph[node].join(', '));
}Check how each node's neighbors are listed in the adjacency list.
The graph has a cycle A->B->C->A. The adjacency list shows each node's neighbors exactly as defined.
What error will the following JavaScript code produce when run?
const graph = new Map(); graph.set('A', ['B']); graph.set('B', ['C']); console.log(graph['A']);
Consider how to access values in a Map object.
Map objects require the get() method to access values, not bracket notation. graph['A'] is undefined.
What will be the output of this JavaScript function that detects if a graph has a cycle?
function hasCycle(graph) {
const visited = new Set();
const stack = new Set();
function dfs(node) {
if (stack.has(node)) return true;
if (visited.has(node)) return false;
visited.add(node);
stack.add(node);
for (const neighbor of graph[node] || []) {
if (dfs(neighbor)) return true;
}
stack.delete(node);
return false;
}
for (const node in graph) {
if (dfs(node)) return true;
}
return false;
}
const graph = {
A: ['B'],
B: ['C'],
C: ['A']
};
console.log(hasCycle(graph));Think about whether the graph contains a cycle.
The graph has a cycle A->B->C->A, so the function returns true.
In a social network, why is a graph a better model than a tree?
Consider how people connect in social networks.
Social networks have complex connections with cycles and multiple links, which graphs can model but trees cannot.
