chore(avl): refactor

Fixes #2

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-05-12 12:20:55 +02:00
parent 705d5cfa17
commit 88d691225e
Signed by: mfocko
GPG key ID: 7C47D46246790496

25
avl.py
View file

@ -124,20 +124,17 @@ class AVLTree(RankedTree[T]):
if rotating_around_root: if rotating_around_root:
self.root = new_root self.root = new_root
return factor == 0 return factor != 0
def __delete_fixup( def __delete_fixup(
self, y: Optional[Node[T]], parent: Optional[Node[T]] = None self, x: Optional[Node[T]], parent: Optional[Node[T]] = None
) -> bool: ) -> bool:
x = y if y else parent
assert x
factor = _balance_factor(x) factor = _balance_factor(x)
if factor == 0: if factor == 0:
_update_rank(x) _update_rank(x)
return False
elif factor in (-1, 1):
return True return True
elif factor in (-1, 1):
return False
rotating_around_root = x.parent is None rotating_around_root = x.parent is None
y, leaning, to_left, to_right = ( y, leaning, to_left, to_right = (
@ -158,11 +155,13 @@ class AVLTree(RankedTree[T]):
def _delete_rebalance( def _delete_rebalance(
self, node: Optional[Node[T]], parent: Optional[Node[T]] self, node: Optional[Node[T]], parent: Optional[Node[T]]
) -> None: ) -> None:
while node or parent: if not node and not parent:
# TODO: Check if it is possible to not propagate all the way up. return
# if self.__delete_fixup(node, parent):
# return if not node:
self.__delete_fixup(node, parent) node, parent = parent, parent.parent
node, parent = parent, (parent.parent if parent else None)
while node and self.__delete_fixup(node, parent):
node, parent = parent, parent.parent if parent else None
# endregion DeleteRebalance # endregion DeleteRebalance