INSERT-RECURSIVE(x, p, z) if x == NIL z.p = p if z.key < p.key p.left = z else p.right = z else if z.key < x.key INSERT-RECURSIVE(x.left, x, z) else INSERT-RECURSIVE(x.right, x, z)
TREE-INSERT-RECURSIVE(T, z) if T.root == NIL T.root = z else INSERT-RECURSIVE(T.root, NIL, z)
ITERATIVE-TREE-SEARCH(x, k) while x ≠ NIL and k ≠ x.key if k < x.key x = x.left else x = x.right return x
TREE-INSERT(T, z) x = T.root // node being compared with z y = NIL // y will be parent of z while x ≠ NIL // descend until reaching a leaf y = x if z.key < x.key x = x.left else x = x.right z.p = y // found the location—insert z with parent y if y == NIL T.root = z // tree T was empty elseif z.key < y.key y.left = z else y.right = z
PARENT(T, z) x = T.root y = NIL while x != NIL and x.key != z.key y = x if z.key < x.key x = x.left else x = x.right if x == NIL return NIL return y
INSERT(T, z) x = T.root y = NIL // pre是z的前驱节点。由于z是叶子节点,因此z的前驱必定在从根节点r到z的路径上。 pre = NIL while x != NIL y = x if z.key < x.key x = x.left else pre = x x = x.right if y == NIL T.root = z else if z.key < y.key y.left = z // z是叶子节点,没有右孩子,因此其后继就是y。 z.succ = y if pre != NIL pre.succ = z else y.right = z z.succ = y.succ y.succ = z
TRANSPLANT'(T, u, v) p = PARENT(T, u) if p == NIL T.root = v else if u == p.left p.left = v else p.right = v // 相比于TRANSPLANT,算法TRANSPLANT'不再考虑父节点指针的指向。
//此为求取z的前驱节点的算法。 PREDECESSOR(T, z) if z.left != NIL return TREE-MAXIMUM(x.left) x = T.root // 此时前驱节点pre必定在从根节点r到z的路径上。 pre = NIL while x != NIL and x.key != z.key if z.key < x.key x = x.left else pre = x x = x.right return pre
DELETE(T, z) pre = PREDECESSOR(T, z) if pre != NIL pre.succ = z.succ if z.left == NIL TRANSPLANT(T, z, z.right) else if z.right == NIL TRANSPLANT(T, z, z.left) else y = TREE-MIMIMUM(z.right) if PARENT(T, y) != z.right TRANSPLANT(T, y, y.right) y.right = z.right TRANSPLANT(T, z, y) y.left = z.left