二叉搜索树-增删查Python
树的高度:节点到叶子节点的最大值就是其高度。
树的深度:高度和深度是相反的,高度是从下往上数,深度是从上往下。因此根节点的深度和叶子节点的高度是 0。
树的层:根开始定义,根为第一层,根的孩子为第二层。
二叉树,三叉树,。。。 N 叉树,由其子节点最多可以有几个决定,最多有 N 个就是 N 叉树
二叉搜索树又名有序二叉树,节点元素按特定次序排布,使得我们可以在查找等操作中使用二分查找提高效率
特点:父节点的值大于左子树任意节点的值,小于右子树任意节点的值
class BinarySearchTree(object): def __init__(self, item): self.item = item self.left = None self.right = None def insert_node(self, value): # 插入节点 if value <= self.item and self.left: self.left.insert_node(value) elif value <= self.item: self.left = BinarySearchTree(value) elif value > self.item and self.right: self.right.insert_node(value) else: self.right = BinarySearchTree(value) def remove_node(self, value, parent): # 删除节点 情况1.叶子节点;情况2.只有左孩子或又孩子;情况3.同时有左右孩子 if value < self.item and self.left: return self.remove_node(value, self) elif value < self.item: return False elif value > self.item and self.right: return self.remove_node(value, self) elif value > self.item: return False else: # 叶子节点 if self.left is None and self.right is None and self == parent.left: parent.left = None self.clear_node() elif self.right is None and self.right is None and self == parent.right: parent.right = None self.clear_node() elif self.left and self.right is None and self == parent.left: parent.left = self.left self.clear_node() elif self.left and self.right is None and self == parent.right: parent.right = self.left self.clear_node() elif self.right and self.left is None and self == parent.left: parent.left = self.right self.remove_node() elif self.right and self.left is None and self == parent.right: parent.right = self.right self.remove_node() else: # 将右子树最小值放到该节点 self.value = self.right.find_minimum_value() self.right.clear_node(self.value, self) def find_node(self, value): # 查找某一节点 if value < self.item and self.left: return self.left.find_node(value) if value > self.item and self.right: return self.right.find_node(value) return value == self.item def find_minimum_value(self): # 找到最小值 if self.left: return self.left.find_minimum_value() else: return self.item def clear_node(self): # 节点清零 self.item = None self.left = None self.right = None if __name__ == '__main__': root = BinarySearchTree(50) root.insert_node(76) root.insert_node(21) root.insert_node(4) root.insert_node(32) root.insert_node(100) root.insert_node(64) root.insert_node(52) print(root.find_node(1000)) print(root.find_minimum_value())
时刻记着自己要成为什么样的人!