def insert(self, val): root = self.root if not root: self.root = make_node(val) return node, parent = _find(root, val) if val < node.value: node.left = make_node(val, node) return self.splay(node.left) node.right = make_node(val, node, right=node.right) if node.right.right: node.right.right.parent = node.right self.splay(node.right)
def delete(self, val): node, parent = _find(self.root, val) if not node.value == val: return if node.left and node.right: next_node, next_node_parent = next_descendant_in_order(node) node.value = next_node.value node, parent = next_node, next_node_parent # now the node will have at most 1 child (i.e 0 or 1 child) child = node.left if node.left else node.right if not parent: node.left = node.right = None if child: child.parent = None self.root = child return if parent.left == node: parent.left = child else: parent.right = child if child: child.parent = parent node.left = node.right = node.parent = None return self.splay(parent)
def delete(self, val): node, parent = _find(self.root, val) if not node.value == val: return if node.left and node.right: next_node, next_node_parent = next_descendant_in_order(node) node.value = next_node.value node, parent = next_node, next_node_parent #now the node will have at most 1 child (i.e 0 or 1 child) child = node.left if node.left else node.right if not parent: node.left = node.right = None if child: child.parent = None self.root = child return if parent.left == node: parent.left = child else: parent.right = child if child: child.parent = parent node.left = node.right = node.parent = None return self.splay(parent)
def find(self, val): node = _find(self.root, val)[0] self.splay(node) if node.value == val: return node