Part 17 / Topic 9 of 12
Build your own binary search tree
A binary search tree (BST) keeps every node's left subtree smaller and right subtree larger than the node itself, which is what makes insert/search/delete all O(log n) — when the tree is balanced. Four traversal orders answer different questions about the same tree:
| Traversal | Visits | Order | Used for |
|---|---|---|---|
| In-order | left, node, right | sorted | reading values out in sorted order |
| Pre-order | node, left, right | root first | copying a tree's exact shape |
| Post-order | left, right, node | root last | deleting a tree safely (children before parent) |
| Level-order (BFS) | one level at a time | top to bottom | printing/visualizing level by level |
private fun insert(node: TreeNode?, value: Int): TreeNode {
if (node == null) return TreeNode(value)
when {
value < node.value -> node.left = insert(node.left, value)
value > node.value -> node.right = insert(node.right, value)
// equal values are ignored -- this BST does not store duplicates
}
return node
}
$ kotlinc TreeDemo.kt -include-runtime -d tree.jar
$ java -jar tree.jar
inserted, in order: [500, 300, 700, 200, 400, 600, 800]
in-order (sorted): [200, 300, 400, 500, 600, 700, 800]
pre-order: [500, 300, 200, 400, 700, 600, 800]
post-order: [200, 400, 300, 600, 800, 700, 500]
level-order (BFS): [[500], [300, 700], [200, 400, 600, 800]]
height: 2
contains(600): true
contains(650): false
-- a skewed tree: inserting already-sorted IDs degrades to a linked list --
inserted, already sorted: [100, 200, 300, 400, 500, 600, 700]
height: 6 (n - 1 for n = 7; a balanced tree holding the same 7 values needs only height 2)
contains(700) now walks every node: O(n), not O(log n) -- this is why self-balancing trees (AVL, red-black) exist
The last block is the caveat worth remembering: inserting already-sorted values into a plain BST produces a tree that is really just a linked list wearing a tree's clothes — every node has only a right child, height is n - 1 instead of the ~log₂(n) a balanced tree would need, and contains degrades from O(log n) to O(n). Self-balancing trees (AVL, red-black) exist specifically to prevent this, by re-shaping the tree on every insert so it never gets this lopsided — on the JVM, java.util.TreeMap/TreeSet are red-black trees under the hood, which is the real reason section 2's "going deeper" note called them out as the O(log n) alternative to hashing.
Full program: examples/trees/TreeDemo.kt.
Done here? The practice set for Part 17 — including the solutions — is on the part page.