DSA interview question
A file-explorer widget shows a folder tree, and its "export as outline" feature writes each folder before its contents: the folder itself, then everything in its first child, then everything in its second child. For a binary tree that's preorder: root, left subtree, right subtree. Recursion expresses it almost word for word, since visiting a subtree is the same problem on a smaller tree.
Example: [1, null, 2, 3] (1 has right child 2, and 2 has left child 3) → [1, 2, 3].
vector<int> preorderTraversal(TreeNode* root);
| Input (level order) | Output | Explanation |
|---|---|---|
[1, null, 2, 3] | [1, 2, 3] | |
[1, 2, 3, 4, 5, null, 8, null, null, 6, 7, 9] | [1, 2, 4, 5, 6, 7, 3, 8, 9] | |
[] | [] | Empty tree |
[1] | [1] | |
[5, 4, 6] | [5, 4, 6] |
(Confirm: the input uses LeetCode's level-order format with null for missing children; values may repeat.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in