What are tree traversal methods?
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).