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
RecursionErrorand the iterative version matters; alistis the stack andcollections.dequeis the queue (list.pop(0)is O(n)); never use a mutable default argument likeout=[].
Code / implementation expected: Yes โ the three recursive orders in Python plus at least one iterative version with a list as the stack.