In a binary search tree, every node's left subtree has smaller values; right subtree larger. Search/insert follow one path from root—O(h) time where h is height.
Search algorithm
- Start at root
- If target == value, found
- If target < value, go left; else right
- Null means missing
Search implementation
#include
struct Node { int v; Node* L; Node* R; };
Node* search(Node* n, int t) {
while (n) {
if (t == n->v) return n;
n = (t < n->v) ? n->L : n->R;
}
return nullptr;
}
int main() {
Node r{8, nullptr, nullptr}, l{3, nullptr, nullptr}, rr{10, nullptr, nullptr};
r.L = &l; r.R = &rr;
std::cout << (search(&r, 3) ? "found\n" : "missing\n");
return 0;
}
Degenerate BST
Inserting sorted 1,2,3,… into plain BST makes a linked list—height n. Use balanced tree or shuffle inserts in production.
Important interview questions and answers
- Q: BST delete overview?
A: Three cases: leaf, one child, two children (replace with inorder successor)—interview follow-up. - Q: map vs own BST?
A: std::map is balanced BST—O(log n) guaranteed; hand-rolled BST must rebalance for guarantees.
Self-check
- What is BST search complexity in terms of height h?
- Why sorted inserts hurt plain BST?
Tip: BST search is O(h)—state height, not always log n without balance.
Interview prep
- Search cost?
O(h) height—O(log n) if balanced.
- std::map?
Balanced BST tree—O(log n) operations.