balance bst

This commit is contained in:
Rowan 2025-06-10 22:41:26 -04:00
parent 446150e4ac
commit d0310c693b
3 changed files with 17 additions and 13 deletions

View file

@ -37,13 +37,14 @@ static func size(node: _Node) -> int:
var right = node.right.map(size).or_default(0)
return left + right + 1
static func _store_in_order(_root: Option, nodes: Array[_Node] = []):
if _root.is_none(): return
static func _store_in_order(_root: Option, nodes: Array[_Node] = []) -> Array[_Node]:
if _root.is_none(): return nodes
var root = _root.unwrap()
_store_in_order(root.left, nodes)
nodes.append(root)
_store_in_order(root.right, nodes)
return nodes
static func _build_balanced_tree(nodes: Array[_Node], start: int = 0, end: int = len(nodes) - 1) -> Option:
if start > end:
@ -58,9 +59,7 @@ static func _build_balanced_tree(nodes: Array[_Node], start: int = 0, end: int =
return Option.some(root)
static func balance(root: _Node) -> Option:
var nodes: Array[_Node] = []
_store_in_order(Option.some(root), nodes)
return _build_balanced_tree(nodes, 0, len(nodes) - 1)
return _build_balanced_tree(_store_in_order(Option.some(root)))
static func has_children(node: _Node) -> bool:
return node.left.is_none() and node.right.is_none()

View file

@ -21,6 +21,15 @@ static func from_iter(iter: Variant) -> Set:
nodes.append(Set.new(value))
return BST._build_balanced_tree(nodes).unwrap()
static func compare(a: Set, b: Set) -> bool:
return a.data < b.data
func balance() -> Set:
var nodes = BST._store_in_order(Option.some(self))
nodes.sort_custom(compare)
return BST._build_balanced_tree(nodes).unwrap()
func is_empty() -> bool:
return value == -1 and not has_children()
@ -73,11 +82,11 @@ func difference(other: Set) -> Set:
diff.insert(value)
return diff.balance()
static func _iter(set: Set) -> Iterator:
static func _iter(_set: Set) -> Iterator:
var iters = Option.collect_some([
set.left.map(_iter),
Option.none if set.value == -1 else Option.some(SingletonIterator.new(set.data)),
set.right.map(_iter)
_set.left.map(_iter),
Option.none if _set.value == -1 else Option.some(SingletonIterator.new(_set.data)),
_set.right.map(_iter)
], true).unwrap()
var iter_arr: Array[Iterator]

View file

@ -11,10 +11,6 @@ var bind_item: Callable = _bind_item
var ring_buffer: RingBuffer
func _ready() -> void:
var a = IntRange.new(0, 6)
var b = IntRange.new(5, 7)
for value in a.difference(b).iter():
print(value)
ring_buffer = RingBuffer.new(items.size(), buffer_size)
ring_buffer.updated.connect(_on_updated)