~/ learn/ comp-372/ cards/ Binary search trees
1 of 5

TREE-INSERT with a trailing pointer (CLRS, iterative)

TREE-INSERT with a trailing pointer (CLRS, iterative)

Answer

TREE-INSERT(T, z): y = NIL x = T.root while x != NIL: y = x if z.key < x.key: x = x.left else: x = x.right z.p = y if y == NIL: T.root = z elif z.key < y.key: y.left = z else: y.right = z

y trails one step behind x; when x falls off the tree, y is exactly the parent to attach z under as a leaf. O(h) — the cost of one root-to-leaf descent.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/6d5f35e3-d1af-4fe7-892b-7485e9db3edc/flashcard utf-8 LF