Balancing
All checks were successful
buildbot/cargo fmt (1.71) Build done.
buildbot/cargo doc (1.71) Build done.
buildbot/cargo clippy (1.71) Build done.
buildbot/cargo test (1.65) Build done.
buildbot/cargo clippy (1.65) Build done.

This commit is contained in:
AF 2023-08-11 12:12:03 +00:00
parent 6192c33341
commit a8af77adf0

View File

@ -40,6 +40,21 @@ trait BinaryTreesAvlExt<'a>: BinaryTreesAvl<'a> {
impl<'a, Trees: BinaryTreesAvl<'a>> BinaryTreesAvlExt<'a> for Trees {}
enum Balancing {
Balanced,
RightBiased,
LeftBiased,
}
fn balancing(hl: u64, hr: u64) -> Balancing {
match (hl.saturating_sub(hr), hr.saturating_sub(hl)) {
(0, 0) | (0, 1) | (1, 0) => Balancing::Balanced,
(0, _) => Balancing::RightBiased,
(_, 0) => Balancing::LeftBiased,
(_, _) => unreachable!(),
}
}
pub trait BinaryTreesAvl<'a>:
BinaryTreesHeight<'a> + BinaryTreesTreeOf<'a> + BinaryTreesTryJoin<'a>
{
@ -78,9 +93,9 @@ pub trait BinaryTreesAvl<'a>:
tr: Self::Tree,
) -> BTWrap<'a, Self, Self::Node> {
let (hl, hr) = (self.height(&tl), self.height(&tr));
match (hl.saturating_sub(hr), hr.saturating_sub(hl)) {
(0, 0) | (0, 1) | (1, 0) => self.try_join(tl, key, tr),
(0, _) => self.assume_bind(&tr, |ctx, trl, kr, trr| {
match balancing(hl, hr) {
Balancing::Balanced => self.try_join(tl, key, tr),
Balancing::RightBiased => self.assume_bind(&tr, |ctx, trl, kr, trr| {
let (hrl, hrr) = (ctx.height(&trl), ctx.height(&trr));
if hrl > hrr {
ctx.assume_bind(&trl, |ctx, trll, krl, trlr| {
@ -90,7 +105,7 @@ pub trait BinaryTreesAvl<'a>:
ctx.make_node((T(tl), key, T(trl)), kr, T(trr))
}
}),
(_, 0) => self.assume_bind(&tl, |ctx, tll, kl, tlr| {
Balancing::LeftBiased => self.assume_bind(&tl, |ctx, tll, kl, tlr| {
let (hll, hlr) = (ctx.height(&tll), ctx.height(&tlr));
if hll < hlr {
ctx.assume_bind(&tlr, |ctx, tlrl, klr, tlrr| {
@ -100,7 +115,6 @@ pub trait BinaryTreesAvl<'a>:
ctx.make_node(T(tll), kl, (T(tlr), key, T(tr)))
}
}),
(_, _) => unreachable!(),
}
}
}