17 releases (9 breaking)
0.10.1 | Oct 27, 2023 |
---|---|
0.10.0 | Jan 28, 2023 |
0.9.2 | Jan 21, 2023 |
#1275 in Data structures
32KB
875 lines
Binary Tree Builder
The library provides an IteratorEx
trait that has a build_tree
method for any iterator of nodes that implement the Node
trait.
The build_tree
function returns the root node of the built tree if it was successfully built, otherwise it returns None
if the provided
iterator is empty.
Node Trait
The Node
trait represents a node in a binary tree. It provides two methods for creating a new parent node from child nodes:
new_parent(self, right: Self) -> Self
: creates a new parent node from two child nodes,new_parent_from_one(self) -> Self
: creates a new parent node from one child node.
The implementation of these methods is specific to the type of node being used, and should be provided by the user.
lib.rs
:
Building a binary tree from an iterator.
Examples
use bin_tree::{IteratorEx, Node};
#[derive(Clone, Default, PartialEq, Eq, Debug)]
struct NodeStr(String);
impl Node for NodeStr {
fn new_parent(self, right: Self) -> Self {
Self("[".to_owned() + &self.0 + ", " + &right.0 + "]")
}
fn new_parent_from_single(self) -> Self {
self
}
}
let x = (0..10).map(|v| NodeStr(v.to_string())).build_tree();
assert_eq!(x, Some(NodeStr("[[[[0, 1], [2, 3]], [[4, 5], [6, 7]]], [8, 9]]".to_string())));