# -*- coding: utf-8 -*-
# @Date : 2019/11/24
# @File : BinarySearchTree.py
'''
动态语言:可以在运行的过程中,修改代码
静态语言:编译时已经确定好代码,运行过程中不能修改
__slots__:限制实例的属性
使用__slots__要注意,
__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
'''
class Node(object):
__slots__ = "_item", "_left", "_right"
def __init__(self, item, left=None, right=None):
self._item = item
self._left = left
self._right = right
class BinarySearchTree(object):
def __init__(self, root=None):
self.__root = root
# 查找
def get(self, key):
# 从根节点开始找
return self.__get(self.__root, key)
def __get(self, node, key):
if node is None:
return None
if key == node._item:
return node._item
if key < node._item:
return self.__get(node._left, key)
else:
return self.__get(node._right, key)
# 添加节点 返回的是重置之后的新Tree
def add(self, value):
self.__root = self.__add(self.__root, value)
def __add(self, node, value):
if node is None:
return Node(value)
# 插入的节点值已经存在
if value == node._item:
pass
else:
# 插入的节点在当前节点的左子树上
if value < node._item:
node._left = self.__add(node._left, value)
# 插入的节点在当前节点的右子树上
else:
node._right = self.__add(node._right, value)
return node
# 删除某节点
def remove(self, key):
pass
def __remove(self, node, key):
if node is None:
return None
if key < node._item:
node._left = self.__remove(node._left, key)
elif key > node._item:
node._right = self.__remove(node._right, key)
else:
# 只有一个孩子节点的情况
if node._left is None:
node = node._right # None or Node
elif node._right is None:
node = node._left
else:
# 当前左子树下面,找到最大值 替换当前的要删除的节点
node._item = self.__get_max(node._left)
# 删除左子树的那个最大值
node._left = self.__remove(node._left, node._item)
return node
# 最小值
def get_min(self):
return self.__get_min(self.__root)
def __get_min(self, node):
if node is None:
return None
while node._left is not None:
node = node._left
return node._item
# 最大值
def get_max(self):
return self.__get_max(self.__root)
def __get_max(self, node):
if node is None:
return None
while node._right is not None:
node = node._right
return node._item
# in order
def print_inorder(self):
self._print_inorder(self.__root)
print("")
def _print_inorder(self, node):
if node is None:
return
self._print_inorder(node._left)
print('[', node._item, ']', end=" ")
self._print_inorder(node._right)
# pre order
def print_preorder(self):
self._print_preorder(self.__root)
print("")
def _print_preorder(self, node):
if node is None:
return
print('[', node._item, ']', end=" ")
self._print_preorder(node._left)
self._print_preorder(node._right)
# post order
def print_postorder(self):
self._print_postorder(self.__root)
print("")
def _print_postorder(self, node):
if node is None:
return
self._print_postorder(node._left)
self._print_postorder(node._right)
print('[', node._item, ']', end=" ")
if __name__ == '__main__':
bst = BinarySearchTree()
numbers = [6, 4, 8, 7, 9, 2, 1, 3, 5, 13, 11, 10, 12]
for i in numbers:
bst.add(i)
bst.print_inorder()
bst.print_postorder()
bst.print_preorder()