What are tree traversal methods?
Why Interviewers Ask This
This is a classic screening question for Data Structures & Algorithms roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
Tree traversal visits every node exactly once. Four standard traversals: (1) In-order (Left, Root, Right): visits left subtree, then root, then right subtree. For BSTs, produces sorted output. Used for: sorted output, validating BST; (2) Pre-order (Root, Left, Right): visits root first, then left, then right. Used for: copying/cloning a tree, serializing a tree (can reconstruct with pre-order + in-order), expression trees (prefix notation); (3) Post-order (Left, Right, Root): visits root last. Used for: deleting a tree (delete children before parent), evaluating expression trees, computing directory sizes; (4) Level-order (BFS): visits level by level from root to leaves using a queue. Used for: shortest path in unweighted trees, printing by level, building a balanced BST. Iterative traversal: use a stack for DFS traversals (avoids recursion stack overflow). Level-order uses a queue. Time: O(n) for all traversals (every node visited once). Space: O(h) for recursive DFS (call stack height), O(w) for BFS (w = max width of tree). For a balanced tree, h = O(log n); for a skewed tree, h = O(n).
Common Mistake
Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong Data Structures & Algorithms candidates.