Trees and Binary Search Trees
A tree has a root node, and each node has children. A binary tree node has at most two children: left and right. Folders on your computer and HTML pages are trees.
Trees model hierarchy: folders on a computer, categories in a shop, the HTML of a web page, a company's org chart. Binary search trees keep data sorted so search, insert and delete are fast. Most tree problems are solved with recursion or a queue (level by level).
Example
Binary Search Tree (BST)
In a BST, everything on the left is smaller and everything on the right is bigger. Searching skips half the tree each step: O(log n) when the tree is balanced. That's why the in-order traversal above came out sorted.
Example
Level-order (breadth-first)
Example
Key points
- A tree has a root, children and leaves.
- DFS (pre/in/post-order) uses recursion; BFS uses a queue.
- In a BST, smaller values go left, bigger right.
📝 Test yourself
1. Which traversal of a BST gives sorted values?
2. What is the search time in a balanced BST?
3. Fill in the structure used for level-order traversal:
q = ([root])
