Skip to the solution
EasyDSA15 min read

What are the tree traversal methods?

142 views

The problem

Question presented to candidate: "Walk me through the ways you can traverse a binary tree. Then, in Python, write preorder, inorder and postorder recursively, write inorder iteratively with a stack, and tell me when you would pick each order."

What a strong answer should cover:

  • The two families: depth-first (preorder, inorder, postorder) and breadth-first (level order with a queue), and that the three DFS orders differ only in when the node is visited.
  • The output of each order on a small example, and that inorder of a BST is sorted.
  • Typical uses: preorder to copy or serialise, inorder for BST problems, postorder when a node needs its children's results, level order for per-level questions.
  • O(n) time for all; O(h) space for DFS (call stack or explicit stack) and O(w) for BFS.
  • Python specifics: the default recursion limit is 1000, so a deep chain raises RecursionError and the iterative version matters; a list is the stack and collections.deque is the queue (list.pop(0) is O(n)); never use a mutable default argument like out=[].

Code / implementation expected: Yes โ€” the three recursive orders in Python plus at least one iterative version with a list as the stack.

  • traversal
  • trees

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 9 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRecursive preorder, inorder, postorder and level order
PythonIterative traversals with an explicit stack, a BST and a 100000-node chain

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 35 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you find a duplicate in an array?

Continue