diff --git a/src/algo/add.rs b/src/algo/add.rs index aac993d..a25e922 100644 --- a/src/algo/add.rs +++ b/src/algo/add.rs @@ -170,36 +170,49 @@ fn _add_recursive( } } - if ctx.getColor(stack.getParent().node.clone()) == Color::BLACK { - return; // todo break - } - if !stack.hasGrandParent() { - ctx.setColor(stack.getParent().node.clone(), Color::BLACK); - return; // todo break - } + unsafe { balance(ctx, stack) } +} - let mut symCtx = - DynamicDirectedBinaryTreeContextFromContext::wrap_mut(ctx, stack.getGrandParent().dir); - let uncle = symCtx.getOppositeChild(stack.getGrandParent().node.clone()); - if let Some(uncle) = uncle { - if ctx.getColor(uncle.clone()) == Color::RED { +unsafe fn balance(ctx: &mut Ctx, stack: &mut Stack>) { + loop { + if ctx.getColor(stack.getParent().node.clone()) == Color::BLACK { + break; + } + if !stack.hasGrandParent() { ctx.setColor(stack.getParent().node.clone(), Color::BLACK); - ctx.setColor(uncle, Color::BLACK); - ctx.setColor(stack.getGrandParent().node.clone(), Color::RED); - return; // todo current = grandparent + break; } - } - match stack.getGrandParent().dir == stack.getParent().dir { - true => { - todo!("__rotateOpposite_Switch(grandParent)"); - stack.replaceTop(stack.pop()); - return; // todo continue + let mut symCtx = + DynamicDirectedBinaryTreeContextFromContext::wrap_mut(ctx, stack.getGrandParent().dir); + + let uncle = symCtx.getOppositeChild(stack.getGrandParent().node.clone()); + if let Some(uncle) = uncle { + if ctx.getColor(uncle.clone()) == Color::RED { + ctx.setColor(stack.getParent().node.clone(), Color::BLACK); + ctx.setColor(uncle, Color::BLACK); + ctx.setColor(stack.getGrandParent().node.clone(), Color::RED); + + if !stack.hasGrandGrandParent() { + break; + } + stack.popDiscard(); + stack.popDiscard(); + continue; + } } - false => { + + if stack.getGrandParent().dir != stack.getParent().dir { todo!("__rotateForward_Forward(parent, grandParent)"); - stack.popDiscard(); - return; // todo current = parent + stack.replaceTop(Frame { + node: stack.getParent().node, + dir: stack.getGrandParent().dir, + }) } + ctx.setColor(stack.getParent().node.clone(), Color::BLACK); + ctx.setColor(stack.getGrandParent().node.clone(), Color::RED); + todo!("__rotateOpposite_Switch(grandParent)"); + + break; } }