[prev] 65 [next]

Randomised BST Insertion (cont)

Approach: normally do leaf insert, randomly do root insert.

insertRandom(tree,item)
|  Input  tree, item
|  Output tree with item randomly inserted
|
|  if tree is empty then
|     return new node containing item
|  end if
|  // p/q chance of doing root insert
|  if random number mod q < p then
|     return insertAtRoot(tree,item)
|  else
|     return insertAtLeaf(tree,item)
|  end if

E.g. 30% chance ⇒ choose p=3, q=10