Beispiel #1
0
 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)
Beispiel #2
0
 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)
Beispiel #3
0
 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)
Beispiel #4
0
 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)
Beispiel #5
0
 def find(self, val):
     node = _find(self.root, val)[0]
     self.splay(node)
     if node.value == val:
         return node
Beispiel #6
0
 def find(self, val):
     node = _find(self.root, val)[0]
     self.splay(node)
     if node.value == val:
         return node