From ba1a8d0533c673fe8b29063a28e540839c99238f Mon Sep 17 00:00:00 2001 From: Andrew Golovashevich Date: Mon, 29 Dec 2025 21:07:42 +0300 Subject: [PATCH] Non-recursive find-and-link --- src/algo/add.rs | 72 +++++++++++++++++++++---------------------------- 1 file changed, 31 insertions(+), 41 deletions(-) diff --git a/src/algo/add.rs b/src/algo/add.rs index 073819b..b4b098e 100644 --- a/src/algo/add.rs +++ b/src/algo/add.rs @@ -112,23 +112,6 @@ impl Stack { } } -fn _getChildFrame( - ctx: &mut Ctx, - node: Ctx::NodeRef, - stack: &mut Stack>, -) -> Option { - let dir = ctx - .determineDirection(node.clone()) - .unwrap_or(BinaryTreeDirection::LEFT); - let child; - match dir { - BinaryTreeDirection::LEFT => child = ctx.getLeftChild(node.clone()), - BinaryTreeDirection::RIGHT => child = ctx.getRightChild(node.clone()), - } - stack.push(Frame { node, dir }); - return child; -} - pub fn add_recursive(ctx: &mut Ctx, newNode: Ctx::NodeRef) { ctx.clearLeftChild(newNode.clone()); ctx.clearRightChild(newNode.clone()); @@ -142,38 +125,45 @@ pub fn add_recursive(ctx: &mut Ctx, newNode: Ctx::NodeRef) { return; } Some(root) => { - let mut stack: Stack> = - Stack::init(&mut [const { MaybeUninit::uninit() }; usize::BITS as usize]); - - let child = _getChildFrame(ctx, root.clone(), &mut stack); - _add_recursive(ctx, &mut stack, child, newNode); - ctx.setColor(root, Color::BLACK) + link(ctx, root, newNode); + balance(ctx); } } } -fn _add_recursive( - ctx: &mut Ctx, - stack: &mut Stack>, - nodeOrPlace: Option, - newNode: Ctx::NodeRef, -) { - match nodeOrPlace { - None => match stack.getParent().dir { - BinaryTreeDirection::LEFT => { - ctx.setLeftRelation(stack.getParent().node.clone(), newNode.clone()) +trait LinkingContext: + BinaryTreeChildrenGetterContext + + BinaryTreeRelationSetterContext + + BinaryTreeDirectionDispatcherClojure +{ + fn stackAddParentInfo(&mut self, node: Self::NodeRef, dir: BinaryTreeDirection); +} + +fn link(ctx: &mut Ctx, mut it: Ctx::NodeRef, newNode: Ctx::NodeRef) { + loop { + let dir = ctx + .determineDirection(it.clone()) + .unwrap_or(BinaryTreeDirection::LEFT); + let child; + match dir { + BinaryTreeDirection::LEFT => child = ctx.getLeftChild(it.clone()), + BinaryTreeDirection::RIGHT => child = ctx.getRightChild(it.clone()), + } + ctx.stackAddParentInfo(it.clone(), dir); + match child { + None => { + match dir { + BinaryTreeDirection::LEFT => ctx.setLeftRelation(it.clone(), newNode), + BinaryTreeDirection::RIGHT => ctx.setRightRelation(it.clone(), newNode), + } + return; } - BinaryTreeDirection::RIGHT => { - ctx.setRightRelation(stack.getParent().node.clone(), newNode.clone()) + Some(child) => { + it = child; + continue; } - }, - Some(node) => { - let child = _getChildFrame(ctx, node, stack); - _add_recursive(ctx, stack, child, newNode); } } - - unsafe { balance(ctx) } } trait BalancingContext: RedBlackTreeColorContext {