What are the external nodes of a binary search tree, and why use them instead of null?
External nodes store no data; they are placeholders at every spot where a child is missing. With them, every node holding data is internal with exactly two children, and a search that fails ends at a concrete node, which is precisely where a new key would be inserted.
In this representation, the tree is a proper binary tree: each internal node has two children, and the leaves are all external placeholders. A tree with n keys has n internal and n + 1 external nodes.
This buys simpler algorithms:
- Search always ends at a node: the internal node holding the key, or the external node marking the gap where the key would have to be.
- Insertion never creates a node from scratch at an arbitrary spot: it converts the external node where the search ended into an internal one, giving it two fresh external children.
- Deletion has a single primitive,
removeExternal(w), which removes an external node together with its parent.
External nodes are the tree's version of the sentinel (guard) nodes of a linked list, the header and trailer that stand in for null. Internal and external nodes can share one node class, and the code never has to check for null. An empty tree is a single external node; implementations often test for "external" as "has no children" and leave key and value empty.