Add function to find leafs.
This commit is contained in:
parent
c243ce751f
commit
9a82b05e45
|
|
@ -1 +1,2 @@
|
||||||
/target
|
/target
|
||||||
|
Cargo.lock
|
||||||
|
|
|
||||||
36
src/lib.rs
36
src/lib.rs
|
|
@ -81,6 +81,21 @@ impl<NodeValueT: NodeValue> Graph<NodeValueT> {
|
||||||
// This is always 0.
|
// This is always 0.
|
||||||
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<Vec<Key>, GraphError> {
|
||||||
|
let mut leaf_keys = Vec::<Key>::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)]
|
#[derive(Debug, Clone)]
|
||||||
|
|
@ -145,4 +160,25 @@ mod tests {
|
||||||
assert!(graph.parent_of(&1).unwrap() == Some(0));
|
assert!(graph.parent_of(&1).unwrap() == Some(0));
|
||||||
assert!(graph.children_of(&1).unwrap().len() == 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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue