← Learning Hub
Intermediate

Trees and Binary Search Trees

A tree has a root node, and each node has children. In a binary tree each node has at most two (left and right). In a binary search tree (BST), smaller values go left and bigger values go right, so search is O(log n) when the tree is balanced.

Trees represent hierarchies and keep data sorted for fast search. Traversals (in-order, level-order) are the tools for almost every tree problem, and TreeMap gives you a balanced tree ready to use.

Example
You can edit this code.

Level-order traversal (BFS)

Example
You can edit this code.

Java's TreeMap

Example
You can edit this code.
TreeMap and TreeSet are balanced trees (red-black trees) inside, so they stay O(log n) even when you insert sorted data. A simple BST like ours can become a slow O(n) 'line' in that case.
Key points
  • BST: smaller left, bigger right.
  • In-order traversal gives sorted order.
  • TreeMap and TreeSet are balanced trees.

📝 Test yourself

1. In a BST, where do smaller values go?
2. Which traversal of a BST gives sorted order?
3. Fill in the TreeMap method for the largest key <= x:
slabs.(750)