def delete_val(self, val): node = self.search(val) if not node: print("node error {}".format(val)) return save_rb_tree(self.root, "{}_delete_pre".format(val)) self.delete_node(node) save_rb_tree(self.root, "{}_delete_after".format(val)) pass
def delete_node(self, node): node_color = node.color val = node.val if not node.left: # 没有左子树 则直接用右子树代替该节点 self._hot = node.parent succ_node = node.right self.transplant(node, succ_node) elif not node.right: succ_node = node.left self._hot = node.parent self.transplant(node, succ_node) else: # 既有左子又有右子,取右子中的最小者替代该节点 new_node = self.findRightMin(node) self._hot = new_node.parent node_color = new_node.color succ_node = new_node.right node.val = new_node.val if new_node.parent != node: new_node.parent.left = succ_node # 用new_node的后继取代newnode,并将newnode作为node右子树的根 # self.transplant(new_node, succ_node) # new_node.right = node.right # new_node.right.parent = new_node # 此时此时以newnode为根的右子树,已完全平衡,可以取代node且不影响平衡 #self.transplant(node, new_node) else: new_node.parent.right = succ_node if succ_node: succ_node.parent = self._hot # 以下代码不能封装到transplant中 ,容易成环,transplant的取代是向上取代 # new_node.left = node.left # new_node.left.parent = new_node # new_node.color = node.color if not self.root: return if self.root == succ_node: self.root.set_black_node() return # 没有后继节点,x为底层节点 # 若x为红色节点可直接删除,此时node_color为原x的颜色,若为黑色,则需调整 #if not succ_node: # succ_node = node if node_color == "B": save_rb_tree(self.root, "{}_delete_mid".format(val)) self.solve_double_black(succ_node)
def delete_node(self, val): node = self.get_node(val) if not node: print("node error {}".format(val)) return save_rb_tree(self.root, "{}_delete_0".format(val)) # 获取真正要删除的节点 node = self.pre_delete_node(node) save_rb_tree(self.root, "{}_delete_1".format(val)) # node 节点必不为空,且子节点也都为空 self.check_delete_node(node) save_rb_tree(self.root, "{}_delete_2".format(val)) #真正删除要删除的节点 self.real_delete_node(node) save_rb_tree(self.root, "{}_delete_3".format(val)) pass
def function(a, b): save_rb_tree(a.root, "{}-{}".format(a.index, a.action)) a.index += 1 func(a, b) save_rb_tree(a.root, "{}-{}".format(a.index, a.action)) a.index += 1
def add_node(self, node): #self.action = 'inser node {}'.format(node.val) self.insert_node(node) save_rb_tree(self.root, "{}_insert_after".format(node.val)) pass