Which statement correctly describes the key structural difference between a graph and a tree?
Think about connectivity and cycles in both structures.
A tree is a special type of graph that is connected and has no cycles. Graphs can be disconnected and may contain cycles.
What is the printed output of this Rust code that builds edges for a tree and a graph?
fn main() {
let tree_edges = vec![(1, 2), (1, 3), (3, 4)];
let graph_edges = vec![(1, 2), (2, 3), (3, 1), (4, 5)];
println!("Tree edges: {:?}", tree_edges);
println!("Graph edges: {:?}", graph_edges);
}Look carefully at the vectors defined for edges.
The code prints exactly the vectors defined for tree_edges and graph_edges without modification.
What error will this Rust code produce when trying to build a tree adjacency list?
use std::collections::HashMap;
fn main() {
let edges = vec![(1, 2), (1, 3), (3, 4)];
let mut adj_list: HashMap<i32, Vec<i32>> = HashMap::new();
for (u, v) in edges {
adj_list.entry(u).or_insert(vec![]).push(v);
adj_list.entry(v).or_insert(vec![]).push(u);
}
println!("Adjacency list: {:?}", adj_list);
}Check if the code uses correct methods to insert and push values.
The code correctly builds an undirected adjacency list by inserting and pushing neighbors. It runs without errors.
Which Rust function correctly detects a cycle in an undirected graph using DFS?
fn has_cycle(node: usize, parent: usize, visited: &mut Vec<bool>, adj: &Vec<Vec<usize>>) -> bool { visited[node] = true; for &neighbor in &adj[node] { if !visited[neighbor] { if has_cycle(neighbor, node, visited, adj) { return true; } } else if neighbor != parent { return true; } } false }
Focus on how the function handles visited nodes and parent node.
This DFS function correctly detects cycles by checking if a visited neighbor is not the parent, indicating a cycle.
Which statement correctly compares the maximum number of edges in a tree and a graph with n nodes?
Recall the definitions of tree edges and maximum edges in simple graphs.
A tree with n nodes always has n-1 edges. A simple undirected graph can have up to n*(n-1)/2 edges connecting every pair of nodes.
