|
| 1 | +class BinarySearchTree: |
| 2 | + def __init__(self, value): |
| 3 | + self.value = value |
| 4 | + self.left = None |
| 5 | + self.right = None |
| 6 | + |
| 7 | + def insert(self, value): |
| 8 | + if value < self.value: |
| 9 | + if not self.left: |
| 10 | + self.left = BinarySearchTree(value) |
| 11 | + else: |
| 12 | + self.left.insert(value) |
| 13 | + |
| 14 | + elif value >= self.value: |
| 15 | + if not self.right: |
| 16 | + self.right = BinarySearchTree(value) |
| 17 | + else: |
| 18 | + self.right.insert(value) |
| 19 | + pass |
| 20 | + |
| 21 | +# searches the binary search tree for the input value, returning a boolean indicating whether the value exists in the tree or not. |
| 22 | + def contains(self, target): |
| 23 | + # compare target to root |
| 24 | + if target == self.value: |
| 25 | + print(f"target {target} == self.value {self.value}") |
| 26 | + return True |
| 27 | + # if it's smaller, check left side |
| 28 | + elif target < self.value: |
| 29 | + print(f"target {target} < self.value {self.value}") |
| 30 | + # first check that there is a left side; if not, return False |
| 31 | + if not self.left: |
| 32 | + print("no self.left") |
| 33 | + return False |
| 34 | + # else, if it doesn't match the left side, call contains on left side with same target |
| 35 | + elif target != self.left: |
| 36 | + print(f"target {target} != self.left {self.left}") |
| 37 | + return self.left.contains(target) |
| 38 | + else: |
| 39 | + print(f"target {target} == self.left {self.left}") |
| 40 | + return True |
| 41 | + # else, check right side |
| 42 | + elif target > self.value: |
| 43 | + print(f"target {target} > self.value {self.value}") |
| 44 | + # first check that there is a right side; if not, return False |
| 45 | + if not self.right: |
| 46 | + print("no self.right") |
| 47 | + return False |
| 48 | + # else, if it doesn't match the right side, call contains on right side with same target |
| 49 | + elif target != self.right: |
| 50 | + print(f"target {target} != self.right {self.right}") |
| 51 | + return self.right.contains(target) |
| 52 | + else: |
| 53 | + print(f"target {target} == self.right {self.right}") |
| 54 | + return True |
| 55 | + pass |
| 56 | + |
| 57 | +# returns the maximum value in the binary search tree. |
| 58 | + def get_max(self): |
| 59 | + # find rightmost node |
| 60 | + max = self |
| 61 | + while max.right: |
| 62 | + max = max.right |
| 63 | + return max.value |
| 64 | + pass |
| 65 | + |
| 66 | +# performs a traversal of _every_ node in the tree, executing the passed-in callback function on each tree node value. |
| 67 | +# There is a myriad of ways to perform tree traversal; in this case any of them should work. |
| 68 | + def for_each(self, cb): |
| 69 | + Inorder |
| 70 | + if self: |
| 71 | + if self.left: |
| 72 | + self.left.for_each(cb) |
| 73 | + cb(self.value) |
| 74 | + if self.right: |
| 75 | + self.right.for_each(cb) |
| 76 | + |
0 commit comments