dsa_rust/algorithms/md_tree_print.rs
1// To make testing/comparing functionality easier,
2// this module imports an existing Heading struct
3// which looks like:
4// pub struct Heading<'a> {
5// level: usize,
6// title: &'a str,
7// }
8use crate::hierarchies::safe_linked_gentree_builder::Heading;
9
10pub fn print_tree_diagram(list: &[Heading]) {
11 // Initial empty list check with early return
12 // Why waste effort on an empty list?
13 if list.is_empty() {
14 println!("\t[]");
15 return;
16 }
17
18 // Phase 1: Creates a normalized list of cloned values (because
19 // list is borrowed) by inserting missing/skipped heading levels
20 // with empty "[]" placeholders.
21 let mut normalized: Vec<Heading> = Vec::new();
22 let mut cur_level = 0;
23 for heading in list {
24 // If there's a generational gap, synthesize intermediate nodes
25 while cur_level + 1 < heading.level {
26 cur_level += 1;
27 normalized.push(Heading {
28 level: cur_level,
29 title: "[]".to_string(),
30 });
31 }
32 // Requires Clone because Heading contains String
33 // which cannot be Copy
34 normalized.push(heading.clone());
35 cur_level = heading.level;
36 }
37
38 // Initial stand-alone leader
39 println!(" │");
40
41 // Phase 2: Match normalized node listing with a stack-based
42 // prefix tracking where each stack entry is a tuple containing
43 // heading level and whether its the last sibling
44 let mut ancestors: Vec<(usize, bool)> = Vec::new();
45
46 // Iterate through the normalized list of nodes
47 for (i, heading) in normalized.iter().enumerate() {
48 // Pop ancestors deeper than or equal to current level
49 while ancestors
50 .last()
51 .is_some_and(|&(lvl, _)| lvl >= heading.level)
52 {
53 ancestors.pop();
54 }
55
56 // Takes the normalized node listing and "peeks" ahead to see
57 // if the current node is the "last" sibling.
58 // If the "next" node.level is < current.level, the node is the last sibling.
59 let is_last = !normalized[i + 1..]
60 .iter()
61 .take_while(|h| h.level >= heading.level)
62 .any(|h| h.level == heading.level);
63
64 // Build box plot prefix/leader
65 let mut prefix = String::new();
66 for &(_, is_last) in &ancestors {
67 prefix.push_str(if is_last { " " } else { "│ " });
68 }
69
70 // Print the node with initial indentation for visual effect
71 println!(
72 " {}{}{}",
73 prefix,
74 if is_last { "└── " } else { "├── " },
75 heading.title
76 );
77
78 ancestors.push((heading.level, is_last));
79 }
80}