How do DFS and BFS on a tree differ, and why does an inorder traversal of a BST come out sorted?
Short answer
DFS goes down one branch then backtracks, using a stack; BFS goes level by level, using a queue. For a BST, an inorder walk (left → root → right) gives an ascending sequence.
3 points to say:
- DFS memory grows with the tree height.
- BFS memory grows with the level width.
- Libraries use self-balancing trees, height O(log n).
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.