Which of the following scenarios cannot be accurately represented by a tree structure?
Think about whether nodes can have multiple parents or cycles.
Trees cannot model relationships where nodes have multiple parents or cycles. Social networks have such connections, so they require graphs.
What is the output of the following C++ code that builds a graph with cycles and prints adjacency lists?
std::unordered_map<int, std::vector<int>> graph; graph[1] = {2, 3}; graph[2] = {3}; graph[3] = {1}; for (auto& [node, neighbors] : graph) { std::cout << node << ": "; for (int n : neighbors) std::cout << n << " "; std::cout << "\n"; }
Check how edges are added and printed exactly.
The graph has edges 1->2, 1->3, 2->3, and 3->1, so adjacency lists print neighbors accordingly.
Given the following code snippet to detect cycles in a graph, what error will occur when run on a tree structure?
bool hasCycle(int node, std::unordered_map<int, std::vector<int>>& graph, std::unordered_set<int>& visited, int parent) { visited.insert(node); for (int neighbor : graph[node]) { if (visited.find(neighbor) == visited.end()) { if (hasCycle(neighbor, graph, visited, node)) return true; } else if (neighbor != parent) { return true; } } return false; } // Called with hasCycle(root, graph, visited, -1);
Consider how the function handles visited nodes and parent tracking.
The function correctly detects cycles by tracking visited nodes and parent. Trees have no cycles, so it returns false without error.
Which data structure best models a city's transportation network where intersections connect multiple roads and some roads form loops?
Think about multiple connections and loops in the network.
Graphs allow multiple connections per node and cycles, which matches transportation networks with loops and multiple roads.
Which statement best explains why graphs are necessary data structures beyond trees?
Consider the structural differences between trees and graphs.
Graphs support multiple parents and cycles, which trees cannot, allowing modeling of complex, non-hierarchical relationships.
