二叉搜索树的创建、遍历、插入、查找、删除
import queue """ 二叉搜索树: 特点:左子树的值小于根节点的值;右子树的值大于根节点的值 1.创建 2.插入节点 3.广度优先遍历 4.根据值查找节点 5.删除节点 """ class TreeNode(object): """定义树的节点""" def __init__(self, val): self.value = val self.father = None self.left = None self.right = None class BinarySearchTree(object): def __init__(self, nodeList): """构建二叉搜索树""" self.root = None for node in nodeList: self.insert(node) def insert(self, node): """插入节点""" father = None cur = self.root # 找到要插入的位置 while cur is not None: if cur.value == node.value: return -1 father = cur if node.value < cur.value: cur = cur.left else: cur = cur.right # 插入节点 node.father = father if father is None: # print("插入根节点") self.root = node elif node.value < father.value: # print("插入左节点") father.left = node else: # print("插入右节点") father.right = node def breadthFirstSearch(self): """广度优先遍历""" if self.root is None: return None resultList = [] q = queue.Queue() q.put(self.root) while not q.empty(): node = q.get() # print(node.value) resultList.append(node.value) if node.left is not None: q.put(node.left) if node.right is not None: q.put(node.right) return resultList def search(self, value): """根据值查找节点""" cur = self.root while cur is not None: if cur.value == value: return cur if value < cur.value: cur = cur.left if value > cur.value: cur = cur.right return None def deleteNode(self, node): """删除节点""" father = node.father # 删除的节点没有左子树,右子树代替删除的节点 if node.left is None: # 删除的节点是根节点 if father is None: self.root = node.right if node.right is not None: node.right.father = None # 删除的节点不是根节点 elif father.left == node: # 删除的节点是左子节点 father.left = node.right if node.right is not None: node.right.father = father else: # 删除的节点是右子节点 father.right = node.right if node.right is not None: node.right.father = father return 1 # 删除的节点有左子树,右子树挂到左子树的最右节点 tmpNode = node.left while tmpNode.right is not None: tmpNode = tmpNode.right tmpNode.right = node.right if node.right is not None: node.right.father = tmpNode # 删除的节点是根节点 if father is None: self.root = node.left node.left.father = None # 删除的节点是左子节点 elif father.left == node: father.left = node.left node.left.father = father # 删除的节点是右子节点 else: father.right = node.left node.left.father = father # node=None return 2 if __name__ == '__main__': data = [24, 34, 5, 4, 8, 23, 45, 35, 28, 6, 29] nodeList = [TreeNode(d) for d in data] # 构建二叉搜索树 bst = BinarySearchTree(nodeList) # 广度优先遍历 print(bst.breadthFirstSearch()) # 根据值查找节点 print(bst.search(23)) node = bst.search(8) # 删除节点 bst.deleteNode(node) print(bst.breadthFirstSearch())