Add ability to get keys in a depth first order.

This commit is contained in:
James Pace 2026-06-20 19:45:51 -04:00
parent 9a82b05e45
commit 9873b6bd52
1 changed files with 28 additions and 0 deletions

View File

@ -96,6 +96,26 @@ impl<NodeValueT: NodeValue> Graph<NodeValueT> {
return Ok(leaf_keys); return Ok(leaf_keys);
} }
/// Return all keys ordered like you were doing
/// a depth first search.
pub fn get_keys_by_depth(&self) -> Result<Vec<Key>, GraphError> {
let mut visited_keys = Vec::<Key>::new();
let mut stack = Vec::<Key>::new();
stack.push(self.root_key());
while stack.len() > 0 {
let next_key = stack.pop().unwrap();
if !visited_keys.contains(&next_key) {
visited_keys.push(next_key);
let children_of_next_key = self.children_of(&next_key)?;
stack.extend(children_of_next_key);
}
}
Ok(visited_keys)
}
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -178,7 +198,15 @@ mod tests {
let fourth_add_res = graph.add(fourth_val, 1); let fourth_add_res = graph.add(fourth_val, 1);
assert!(fourth_add_res.is_ok()); assert!(fourth_add_res.is_ok());
let fifth_val = NodeType::new(5.0);
let fifth_add_res = graph.add(fifth_val, 2);
assert!(fifth_add_res.is_ok());
let leaf_keys = graph.find_leaf_keys().unwrap(); let leaf_keys = graph.find_leaf_keys().unwrap();
assert!(leaf_keys.len() == 2); assert!(leaf_keys.len() == 2);
let keys_by_depth = graph.get_keys_by_depth().unwrap();
let expected_keys_by_depth = vec![0, 2, 4, 1, 3];
assert!(keys_by_depth == expected_keys_by_depth);
} }
} }