1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
| class TreeNode: def __init__(self, key=None): self.__key = key self.__left = None self.__right = None
@property def key(self): return self.__key
@key.setter def key(self, key): self.__key = key
@property def left(self): return self.__left
@left.setter def left(self, left): self.__left = left
@property def right(self): return self.__right
@right.setter def right(self, right): self.__right = right
class BST: def __init__(self): self.__root = None
@property def root(self): return self.__root
def preorder(self, cur): if not cur: return
print(cur.key, end = " ") self.preorder(cur.left) self.preorder(cur.right) def insert(self, key): new_node = TreeNode(key)
cur = self.__root
if not cur: self.__root = new_node return while True: parent = cur if key < cur.key: cur = cur.left if not cur: parent.left = new_node return else: cur = cur.right if not cur: parent.right = new_node return def search(self, target): cur = self.__root
while cur: if cur.key == target: return cur elif cur.key > target: cur = cur.left
else: cur = cur.right return None def delete(self, target): self.__root = self.__delete_recursion(self.__root, target)
def __delete_recursion(self, cur, target): if not cur: return None elif target < cur.key: cur.left = self.__delete_recursion(cur.left, target) elif target > cur.key: cur.right = self.__delete_recursion(cur.right, target) else: if not cur.left and not cur.right: cur = None
elif not cur.right: cur = cur.left
elif not cur.left: cur = cur.right
else: rep = cur.left while rep.right: rep = rep.right cur.key, rep.key = rep.key, cur.key
cur.left = self.__delete_recursion(cur.left, rep.key)
return cur
if __name__ == "__main__": bst = BST()
bst.insert(6) bst.insert(3) bst.insert(8) bst.insert(2) bst.insert(4) bst.insert(10) bst.insert(9) bst.insert(11)
bst.preorder(bst.root) print() bst.insert(5) bst.preorder(bst.root)
print()
ret = bst.search(13) if ret: print(f"{ret.key} is found.") else: print("No such data.")
bst.delete(6)
bst.preorder(bst.root)
|