|
| 1 | +''' |
| 2 | +Overview: |
| 3 | +Linked List is a non-forking tree |
| 4 | +
|
| 5 | +Binary Tree = Node with 2 other nodes branching off |
| 6 | +Full Tree = Node with every node either pointing to 0 or 2 nodes |
| 7 | +Perfect Tree = Any level is completely filled all the way across |
| 8 | +Complete Tree = Filled tree, left-to-right, with no gaps |
| 9 | +
|
| 10 | +Parent Node - Child Node |
| 11 | +1 Parent for a node |
| 12 | +Leaf = Childless Nodes |
| 13 | +
|
| 14 | +Binary Search Tree = Start at parent node, if larger value, go right, smaller, go left. |
| 15 | + compare with each child node until at leaf. |
| 16 | +As the tree grows, nodes = 2^levels - 1 |
| 17 | +Takes O(log(nodes)) = O(log n) steps to find/append/pop a particular node |
| 18 | +Divide & Conquer because of left/right for lesser/greater |
| 19 | +That's for most trees (Ideal case is Perfect Tree) |
| 20 | +
|
| 21 | +Worst Case, if tree never forks, all values on one side |
| 22 | +It's a Linked List. O(n) lookup/insert/remove |
| 23 | +
|
| 24 | +Lookup: LL O(n), BST O(log n) |
| 25 | +Remove: LL O(n), BST O(log n) |
| 26 | +Insert: LL O(1), BST O(log n) cuz of traversal |
| 27 | +LL is very quick with appending, no other DS beats it |
| 28 | +''' |
| 29 | + |
| 30 | + |
| 31 | +class Node: |
| 32 | + def __init__(self, value): |
| 33 | + self.value = value |
| 34 | + self.left = None |
| 35 | + self.right = None |
| 36 | + |
| 37 | + |
| 38 | +class BinarySearchTree: |
| 39 | + def __init__(self): |
| 40 | + self.root = None # Empty Tree Initialization |
| 41 | + |
| 42 | + def insert(self, value): |
| 43 | + new_node = Node(value) |
| 44 | + if self.root is None: |
| 45 | + self.root = new_node |
| 46 | + return True |
| 47 | + temp = self.root |
| 48 | + while True: |
| 49 | + if value == temp.value: |
| 50 | + return False |
| 51 | + if value < temp.value: |
| 52 | + if temp.left: |
| 53 | + temp = temp.left |
| 54 | + else: |
| 55 | + temp.left = new_node |
| 56 | + return True |
| 57 | + else: |
| 58 | + if temp.right: |
| 59 | + temp = temp.right |
| 60 | + else: |
| 61 | + temp.right = new_node |
| 62 | + return True |
| 63 | + |
| 64 | + def contains(self, value): |
| 65 | + temp = self.root |
| 66 | + while temp: |
| 67 | + if temp.value == value: |
| 68 | + return True |
| 69 | + if value < temp.value: |
| 70 | + temp = temp.left |
| 71 | + else: |
| 72 | + temp = temp.right |
| 73 | + return False |
0 commit comments