SteelReed

Search

Search posts, questions…

Collections & DSAQuestion 19 / 25

Junior

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.

stack / recursionqueueinorder on a BSTTraverse a treeDFS: whole branchmemory O(h)BFS: level by levelmemory O(w)preorder, inorder,postorderAscending orderLevel-order

3 points to say:

  1. DFS memory grows with the tree height.
  2. BFS memory grows with the level width.
  3. 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.