Browse Source

Finished balance method and added a tree height method

master
Raphael Roberts 6 years ago
parent
commit
b7ccd2283a
  1. 35
      BST.py

35
BST.py

@ -45,11 +45,11 @@ class BST:
@classmethod
def balance(cls, list_param):
tree = cls()
add_rec(0, len(list_param) // 2, len(list_param), list_param, tree)
add_rec(0, len(list_param) - 1, list_param, tree)
return tree
iteration_count = 0
def height(self):
return rec_height(self.root)
def inOrderRec(top, ret):
@ -62,24 +62,27 @@ def inOrderRec(top, ret):
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()
def rec_height(node: BSTNode):
if node is None:
return 0
return 1 + max(map(rec_height, (node.left, node.right)))
def add_rec(start, end, list_param, tree: BST):
if end - start >= 0:
mid = (start + end) // 2
tree.add(list_param[mid])
add_rec(start, mid - 1, list_param, tree)
add_rec(mid + 1, end, list_param, tree)
if __name__ == "__main__":
list_param = list(range(17))
test = 17
list_param = list(range(test))
tree = BST.balance(list_param)
tree2 = BST()
for i in range(17):
for i in range(test):
tree2.add(i)
r = list(node.value for node in tree.inOrder())
r2 = list(node.value for node in tree2.inOrder())
assert r == r2
Loading…
Cancel
Save