- All the values in the left-hand subtree of N are less than the value at N.
- All the values in the right-hand subtree of N are greater than the value at N.

boolean search(V,N) { // search for value V in the subtree with root N; if (N==null) return false; else if (V= N.value) return true; else if (V < N.value) return search(V,N.left); else return search(V,N.right) // V > N.valueExample:

void add(V,N) { if (V < N.value) { if (N.left != null) add(V,N.left) else { create new node P for V; N.left = P; } } else if (V > N.value) if (N.right!= null) add(V,N.right) else { create new node P for V; N.right= P; } } }

- Case 1: V isn't in the tree. Don't do anything.
- Case 2: V is at node P which is a leaf. Delete P.
- Case 3:
V is at an internal node P with only one child C. Move C into P's
position.
Case 4: V is at an internal node P with two children. Let Q be either the node immediately before P, which is the rightmost descendant of P.left, or the node immediately after P, which is the leftmost descendant of P.right. In either case, Q does not have two children (if it did, it wouldn't be leftmost/rightmost) so either:

- Case 4A: Q is a leaf. Move Q.value into P.value, and delete Q.
- Case 4B: Q has one child C. This must be a left child, since Q is the rightmost descendent. Move Q.value into P.value and move C into Q's position.

void delete(V,N) { if (N == null) return; // Case 1 if (V < N.value) delete(V,N.left); // recursively go down the tree else if (V > N.value) delete(V,N.right) // recursively go down the tree else // V == N.value if (N is a leaf) deleteLeaf(N); // Case 2 else if (N.left==null) // Case 3 replaceNode(N.right, N); else if (N.right==null) // Case 3 replaceNode(N.left, N); else { // Case 4 Q = N.left.rightmostDescendant(); N.value = Q.value; if (Q is a leaf) // Case 4.A deleteLeaf(Q); else // Case 4.B replaceNode(Q.left,Q) } } void deleteLeaf(L) { P = L.parent; if (L == P.left) L.left = null; else L.right=null; } void replaceNode(C,N) { // Replace N by C; P = N.parent; C.parent = P; if (N == P.left) P.left = C; else P.right=C; }

****************************************************************************

****************************************************************************

****************************************************************************

In the best case, every internal node (except possibly one in
second-to-last row) has two children. Then N is between 2^{H-1} and
2^{H}-1, so H is about
log_{2}(N)) plus or minus 1.

In the worst case, every internal node has exactly one child, and there is only one leaf in the tree. In that case the tree is essentially just a linked list and H = N.