# An introduction to binary search and red-black trees

We also need to make sure that any subtrees of P and S if S is not null end up in the appropriate place once the restructuring is done. K 's parent P is red. Note that P 's parent, G, K 's grandparent must be black why? One consequence of this is that lookupinsertand delete on a balanced search tree an introduction to binary search and red-black trees be done in O log N worst-case time.

If that is the case, then we recursively handle the double-red situation starting at G and G 's parent instead of K and K 's parent. The second step is to color the new node red. This step is O 1 since it just requires setting the value of one node's color field.

So, in the worst-case, the restructuring that is done during insert is O 1. In order to handle this double-red situation, we will need to consider the color of G 's other child, that is, P 's sibling, S. If we were to use external nodes in a binary search tree, then the children of a leaf node would be external an introduction to binary search and red-black trees and not nullthat is:. K 's parent P is red. It will be easier to describe the algorithms for inserting and deleting on a red-black tree if we use external nodes it cuts out a number of situations where we would otherwise have to worry about null.

You will not be responsible for knowing the details of how to delete a key from a red-black tree. If that is the case, then we recursively handle the double-red situation starting at G and G's parent instead of K and K's parent. Because a red-black tree is a binary search tree and operations that don't change the structure of a tree won't affect whether the tree satisfies the red-black tree properties, the lookup and print an introduction to binary search and red-black trees are identical to lookup and print for binary search trees. So lookupinsertand delete will always be logarithmic in the number of nodes but insert and delete may be more complicated than for binary search trees.

Once a restructuring is done, the insert algorithm is done, so at most 1 restructuring is done in step 3. Once a restructuring is done, the insert algorithm is done, so at most 1 restructuring is done in step 3. Before we describe what red-black trees are, it will be useful to introduce the concept of an external node.