diff --git a/.gitignore b/.gitignore index ea8c4bf..96ef6c0 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +Cargo.lock diff --git a/src/lib.rs b/src/lib.rs index 4402b38..a98c81e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -81,6 +81,21 @@ impl Graph { // This is always 0. 0 } + + /// Find all nodes that are leaf nodes. + /// A leaf node is one that doesn't have any children. + pub fn find_leaf_keys(&self) -> Result, GraphError> { + let mut leaf_keys = Vec::::new(); + + for key in 0..self.nodes.len() { + let children_of_node = self.children_of(&key)?; + if children_of_node.len() == 0 { + leaf_keys.push(key); + } + } + + return Ok(leaf_keys); + } } #[derive(Debug, Clone)] @@ -145,4 +160,25 @@ mod tests { assert!(graph.parent_of(&1).unwrap() == Some(0)); assert!(graph.children_of(&1).unwrap().len() == 0); } + + #[test] + fn graph_search() { + let root_val = NodeType::new(1.0); + let mut graph = Graph::new(root_val); + + let second_val = NodeType::new(2.0); + let second_add_res = graph.add(second_val, 0); + assert!(second_add_res.is_ok()); + + let third_val = NodeType::new(3.0); + let third_add_res = graph.add(third_val, 0); + assert!(third_add_res.is_ok()); + + let fourth_val = NodeType::new(4.0); + let fourth_add_res = graph.add(fourth_val, 1); + assert!(fourth_add_res.is_ok()); + + let leaf_keys = graph.find_leaf_keys().unwrap(); + assert!(leaf_keys.len() == 2); + } }