|
|
@ -0,0 +1,85 @@ |
|
|
|
|
|
class BSTNode: |
|
|
|
|
|
def __init__(self, value): |
|
|
|
|
|
self.value = value |
|
|
|
|
|
self.left = None |
|
|
|
|
|
self.right = None |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class BST: |
|
|
|
|
|
def __init__(self): |
|
|
|
|
|
self.root = None |
|
|
|
|
|
self.size = 0 |
|
|
|
|
|
|
|
|
|
|
|
def clear(self): |
|
|
|
|
|
self.root = None |
|
|
|
|
|
self.size = 0 |
|
|
|
|
|
|
|
|
|
|
|
def add(self, value): |
|
|
|
|
|
to_add = BSTNode(value) |
|
|
|
|
|
if self.root is None: |
|
|
|
|
|
self.root = to_add |
|
|
|
|
|
self.size += 1 |
|
|
|
|
|
else: |
|
|
|
|
|
current = self.root |
|
|
|
|
|
parent = None |
|
|
|
|
|
while current is not None: |
|
|
|
|
|
if value > current.value: |
|
|
|
|
|
parent = current |
|
|
|
|
|
current = current.right |
|
|
|
|
|
elif value < current.value: |
|
|
|
|
|
parent = current |
|
|
|
|
|
current = current.left |
|
|
|
|
|
else: |
|
|
|
|
|
return |
|
|
|
|
|
if value > parent.value: |
|
|
|
|
|
parent.right = to_add |
|
|
|
|
|
else: |
|
|
|
|
|
parent.left = to_add |
|
|
|
|
|
self.size += 1 |
|
|
|
|
|
|
|
|
|
|
|
def inOrder(self): |
|
|
|
|
|
ret = [] |
|
|
|
|
|
inOrderRec(self.root, ret) |
|
|
|
|
|
return ret |
|
|
|
|
|
|
|
|
|
|
|
@classmethod |
|
|
|
|
|
def balance(cls, list_param): |
|
|
|
|
|
tree = cls() |
|
|
|
|
|
add_rec(0, len(list_param) // 2, len(list_param), list_param, tree) |
|
|
|
|
|
return tree |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
iteration_count = 0 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def inOrderRec(top, ret): |
|
|
|
|
|
if top is None: |
|
|
|
|
|
return |
|
|
|
|
|
if top.left: |
|
|
|
|
|
inOrderRec(top.left, ret) |
|
|
|
|
|
ret.append(top) |
|
|
|
|
|
if top.right: |
|
|
|
|
|
inOrderRec(top.right, ret) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def add_rec(start, mid, end, list_param, tree: BST): |
|
|
|
|
|
global iteration_count |
|
|
|
|
|
iteration_count += 1 |
|
|
|
|
|
if iteration_count < 60: |
|
|
|
|
|
if start != mid and mid != end: |
|
|
|
|
|
print(mid) |
|
|
|
|
|
add_rec(start, (start + mid) // 2, mid, list_param, tree) |
|
|
|
|
|
tree.add(list_param[mid]) |
|
|
|
|
|
add_rec(mid, (mid + end) // 2, end, list_param, tree) |
|
|
|
|
|
else: |
|
|
|
|
|
breakpoint() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
list_param = list(range(17)) |
|
|
|
|
|
tree = BST.balance(list_param) |
|
|
|
|
|
tree2 = BST() |
|
|
|
|
|
for i in range(17): |
|
|
|
|
|
tree2.add(i) |
|
|
|
|
|
r = list(node.value for node in tree.inOrder()) |
|
|
|
|
|
r2 = list(node.value for node in tree2.inOrder()) |