triangle-exclamationBinary Search Tree (BST)

About

A Binary Tree in which:

  • The left child contains values smaller than the parent.

  • The right child contains values greater than the parent.

Drawing

Searching an element

circle-info

Runs on O(logN)O(log N ) up to O(N)O(N) in the worst case, depending on how the Tree structure is.

Inserting an element

Just look for the place that satisfy BST conditions and add.

circle-info

Will eventually unbalance the tree.

Deleting an element

Deleting is bit more complicated and have 3 separate cases to look for:

  • Case 1: The deleted node XX has no children, so AncestorXAncestor_X just points to undefined.

  • Case 2: The deleted node XX has only 1 child, so AncestorXAncestor_X points to XX child.

  • Case 3: The deleted node XX has both children, so AncestorXAncestor_X will point to either:

    • The largest decendent node of Xleft childX_{left\ child}. (largest on small side)

    • The smallest decendent node of Xright childX_{right\ child}. (smallest on large side)

circle-info

Having a height property on each node, helps choosing in Case 3 which child has the highest height.

And choosing the child with the highest helps pruning the tree and reducing its height.

Last updated