DSA interview question
A code-analysis service walks huge abstract syntax trees, some thousands of levels deep, and recursion overflows the call stack. The traversal must be rewritten with an explicit stack. For preorder (node, left, right), pop a node, record it, then push its right child before its left child. The stack is last-in first-out, so the left subtree is processed first.
Example: [1, 2, 3, 4, 5, 6, 7] → [1, 2, 4, 5, 3, 6, 7].
vector<int> preorderIterative(TreeNode* root);
| Input (level order) | Output | Explanation |
|---|---|---|
[1, null, 2, 3] | [1, 2, 3] | |
[1, 2, 3, 4, 5, 6, 7] | [1, 2, 4, 5, 3, 6, 7] | |
[1, 2, null, 3] | [1, 2, 3] | A left chain |
[1, null, 2, null, 3] | [1, 2, 3] | A right chain |
[] | [] |
(Confirm: no recursion; the output matches recursive preorder.)
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