This commit is contained in:
AF 2023-05-30 00:59:31 +00:00
parent 5858fbd897
commit 6be1000993

View File

@ -26,6 +26,14 @@ impl<A: Display> Display for AvlN<A> {
}
}
#[cfg(test)]
impl<A> AvlN<A> {
fn balanced(&self) -> bool {
let (lh, rh) = (self.l.height, self.r.height);
std::cmp::max(lh, rh) - std::cmp::min(lh, rh) < 2 && self.l.balanced() && self.r.balanced()
}
}
struct AvlR<A> {
node: Rc<AvlN<A>>,
}
@ -44,6 +52,13 @@ impl<A: Display> Display for AvlR<A> {
}
}
#[cfg(test)]
impl<A> AvlR<A> {
fn balanced(&self) -> bool {
self.node.balanced()
}
}
struct AvlT<A> {
reference: Option<AvlR<A>>,
height: u64,
@ -67,6 +82,16 @@ impl<A: Display> Display for AvlT<A> {
}
}
#[cfg(test)]
impl<A> AvlT<A> {
fn balanced(&self) -> bool {
match &self.reference {
Some(reference) => reference.balanced(),
None => true,
}
}
}
struct AvlTs<A> {
_a: PhantomData<A>,
}
@ -170,3 +195,29 @@ impl<'a, A: 'a + PartialOrd> BinaryTreesAvl<'a> for AvlTs<A> {
AvlN { l: tl, r: tr, key }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let trees = AvlTs::new();
let mut tree = trees.empty();
for i in [
8, 3, 10, 17, 0, 13, 6, 1, 11, 5, 4, 7, 18, 14, 15, 9, 2, 19, 16, 12,
] {
tree = trees.clone().add_tree(tree, i.into());
assert!(tree.balanced());
// println!("{} {}", tree.height, tree);
}
for i in [
2, 9, 4, 7, 8, 10, 17, 1, 13, 15, 18, 12, 5, 0, 3, 6, 16, 19, 14, 11,
] {
tree = trees.clone().remove(tree, i.into());
assert!(tree.balanced());
// println!("{} {}", tree.height, tree);
}
// assert!(false);
}
}