You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.1 KiB

  1. class BSTNode:
  2. def __init__(self, value):
  3. self.value = value
  4. self.left = None
  5. self.right = None
  6. class BST:
  7. def __init__(self):
  8. self.root = None
  9. self.size = 0
  10. def clear(self):
  11. self.root = None
  12. self.size = 0
  13. def add(self, value):
  14. to_add = BSTNode(value)
  15. if self.root is None:
  16. self.root = to_add
  17. self.size += 1
  18. else:
  19. current = self.root
  20. parent = None
  21. while current is not None:
  22. if value > current.value:
  23. parent = current
  24. current = current.right
  25. elif value < current.value:
  26. parent = current
  27. current = current.left
  28. else:
  29. return
  30. if value > parent.value:
  31. parent.right = to_add
  32. else:
  33. parent.left = to_add
  34. self.size += 1
  35. def inOrder(self):
  36. ret = []
  37. inOrderRec(self.root, ret)
  38. return ret
  39. @classmethod
  40. def balance(cls, list_param):
  41. tree = cls()
  42. add_rec(0, len(list_param) // 2, len(list_param), list_param, tree)
  43. return tree
  44. iteration_count = 0
  45. def inOrderRec(top, ret):
  46. if top is None:
  47. return
  48. if top.left:
  49. inOrderRec(top.left, ret)
  50. ret.append(top)
  51. if top.right:
  52. inOrderRec(top.right, ret)
  53. def add_rec(start, mid, end, list_param, tree: BST):
  54. global iteration_count
  55. iteration_count += 1
  56. if iteration_count < 60:
  57. if start != mid and mid != end:
  58. print(mid)
  59. add_rec(start, (start + mid) // 2, mid, list_param, tree)
  60. tree.add(list_param[mid])
  61. add_rec(mid, (mid + end) // 2, end, list_param, tree)
  62. else:
  63. breakpoint()
  64. if __name__ == "__main__":
  65. list_param = list(range(17))
  66. tree = BST.balance(list_param)
  67. tree2 = BST()
  68. for i in range(17):
  69. tree2.add(i)
  70. r = list(node.value for node in tree.inOrder())
  71. r2 = list(node.value for node in tree2.inOrder())