Algorithms from zero
Trees: multiple-choice review
Six questions that cut across the whole unit. Each one is a decision you make when you reach for a tree in real code — not a definition to recite, but which traversal, which invariant, which complexity is actually in play.
Confirm you can connect node structure, traversal choice, the BST invariant, balance, BFS-vs-DFS, and the tree-DP pattern — the synthesis the individual lessons built toward.
You must return the values of a binary search tree in ascending sorted order. Which single traversal does this directly, and why?
A teammate inserts the keys 1, 2, 3, 4, 5, 6, 7 into an empty BST in that exact order, then complains that search is slow. What happened, and what is the height?
You need every node grouped by its depth — all of level 0, then all of level 1, and so on. Which approach fits, and what is the key implementation detail?
In the standard recurse-and-combine pattern for trees, what does the base case return for an empty subtree when computing height (with the convention that a leaf has height 0)?
Computing the diameter of a binary tree (longest path between any two nodes), why does each recursive call return the subtree's height while the diameter is kept in a side variable?
Two engineers compare an in-order recursive traversal and a level-order (BFS) traversal of the same balanced tree with n nodes. What is the dominant extra-space cost of each?
The through-line of the unit is one mapping: the shape of the data dictates the tool. A binary tree is a node with two subtrees, so recursion is the natural walk; the three DFS orders differ only in when the node is visited, and in-order is the one that reads a BST out sorted. The BST invariant buys O(h) search — but only balance keeps h near log n, and sorted-order insertion is the worst case that collapses it to O(n). BFS with a per-level size snapshot is the tool when depth matters, trading the stack for a queue. And tree DP returns local information up while accumulating the global answer on the side — one pass, two quantities.