One set interface can exploit several structural promises.
Compare unordered lists, ordered lists, and binary search trees while keeping membership and adjoin questions separate from representation-specific traversal.
Which operations become cheaper when a set representation promises order or a search-tree shape?
- Implement membership and adjoin for an unordered-list set
- Use increasing order to stop membership early and insert in place
- Follow one branch at each binary-search-tree comparison
- Convert a tree set to an ordered sequence without changing membership meaning
- Compare balance and search cost across finite tree shapes
An unordered-list set can place a new element at the front after checking for duplicates. An ordered-list set pays attention to increasing order: if the current element is already larger than the target, membership can stop and adjoin can insert before it. The abstract questions are the same, but the representation invariant changes the process.
A binary search tree stores smaller entries on the left and larger entries on the right. Each comparison chooses one branch instead of scanning every entry. tree->list performs an in-order traversal and recovers an ordered sequence. The balanced hand-built tree demonstrates the search rule, while a one-sided tree exposes a linear path.
- Output
- —
- Value
- —
- Diagnostic
- —
The list-set program returns ((1 3 5) (4 1 3 5) #f (1 3 4 5 7)). The tree program returns (#t #f (1 3 4 5 7 8 9)).
Compare the unordered scan with the ordered early stop before 5. In ordered-adjoin, find the single insertion point. In the tree, record whether each comparison selects the left or right branch, then contrast that path with the complete in-order traversal used by tree->list.
Change the program and compare the result.
Implement adjoin-tree and insert 6 into the sample tree. Confirm membership and the ordered tree->list result, then create a deliberately one-sided tree and compare its linear search path with the logarithmic path of a balanced tree.
Show hint
Reuse the same three comparison cases as tree-member?, rebuilding only the branch that receives the new value.