Graphs and trees
Quick answer
Graphs connect vertices by edges; trees organize hierarchical relationships. Index-based storage often makes shared relationships easier to represent safely in Rust.
Traversal and visited state
Breadth-first search uses a queue and marks visited vertices to avoid repeated traversal in cyclic graphs. For adjacency lists its usual time bound is O(V+E), assuming constant-time visited checks. An owned tree can instead use nested Vec<Node> children. Validate externally supplied indices before using them.
use std::collections::VecDeque;fn main() { let graph = [vec![1, 2], vec![2], vec![0]]; let mut seen = [false; 3]; let mut q = VecDeque::from([0usize]); seen[0] = true; let mut order = vec![]; while let Some(v) = q.pop_front() { order.push(v); for &w in &graph[v] { if !seen[w] { seen[w] = true; q.push_back(w); } } } println!("{order:?}");}Expected stdout (not executed):
[0, 1, 2]All indices are valid by construction here.
struct Node { children: Vec<Node> }fn count(n: &Node) -> usize { 1 + n.children.iter().map(count).sum::<usize>() }fn main() { let root = Node { children: vec![Node { children: vec![] }] }; println!("{}", count(&root));}Expected stdout (not executed):
2Recursion follows owned children; deep untrusted trees may need an explicit stack.
Common mistake
Do not traverse a cyclic graph without tracking visited vertices.
Try it yourself
Add a disconnected fourth vertex and explain why it is not visited from vertex zero.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Graphs and trees — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A graph can contain a self-loop. What should BFS do when discovering a vertex?
Graphs and trees — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::collections::VecDeque; fn main() { let graph = [vec![1, 2], vec![2], vec![0]]; let mut seen = [false; 3]; let mut q = VecDeque::from([0usize]); seen[0] = true; let mut order = vec![]; while let Some(v) = q.pop_front() { order.push(v); for &w in &graph[v] { if !seen[w] { seen[w] = true; q.push_back(w); } } } println!("{order:?}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Graphs and trees — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust struct Node { children: Vec<Node> } fn count(n: &Node) -> usize { 1 + n.children.iter().map(count).sum::<usize>() } fn main() { let root = Node { children: vec![Node { children: vec![] }] }; println!("{}", count(&root)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.