Which of the following statements correctly describes the key structural difference between a graph and a tree?
Think about connectivity and cycles in trees and graphs.
A tree is a special type of graph that is connected and has no cycles. Graphs can be disconnected and may contain cycles.
Consider a graph and a tree each with 5 nodes. What is the number of edges in the tree?
int nodes = 5; int treeEdges = nodes - 1; int graphEdges = 7; // example graph edges std::cout << treeEdges << std::endl;
Recall the formula for edges in a tree with n nodes.
A tree with n nodes always has n-1 edges.
What error will occur when running the following C++ code that tries to detect a cycle in a tree represented as an adjacency list?
std::vector<std::vector<int>> adj = {{1}, {0, 2}, {1, 3}, {2, 1}}; std::vector<bool> visited(4, false); bool hasCycle(int node, int parent) { visited[node] = true; for (int neighbor : adj[node]) { if (!visited[neighbor]) { if (hasCycle(neighbor, node)) return true; } else if (neighbor != parent) { return true; } } return false; } int main() { bool cycle = hasCycle(0, -1); std::cout << (cycle ? "Cycle detected" : "No cycle") << std::endl; return 0; }
Check the adjacency list for cycles and how the function detects them.
The adjacency list contains a cycle between nodes 1, 2, and 3, so the function correctly detects a cycle and outputs "Cycle detected".
Given the following adjacency list for a graph, what is the BFS traversal order starting from node 0?
std::vector<std::vector<int>> adj = {{1, 2}, {0, 3}, {0, 3}, {1, 2}}; std::vector<int> bfs(int start) { std::vector<int> order; std::queue<int> q; std::vector<bool> visited(adj.size(), false); q.push(start); visited[start] = true; while (!q.empty()) { int node = q.front(); q.pop(); order.push_back(node); for (int neighbor : adj[node]) { if (!visited[neighbor]) { visited[neighbor] = true; q.push(neighbor); } } } return order; } int main() { auto order = bfs(0); for (int n : order) std::cout << n << " "; return 0; }
BFS visits neighbors level by level in the order they appear in adjacency list.
Starting at 0, neighbors 1 and 2 are visited in order. Then neighbors of 1 (3) and 2 (3) are visited, but 3 is visited once.
Why does a tree have exactly one simple path between any two nodes?
Think about what acyclic and connected mean for paths.
Since trees are connected and have no cycles, there is only one unique path between any two nodes.
