DSA interview question
A build system must compile modules so that every dependency is built before the module that needs it: children before the parent, which is postorder. The team wants it without recursion. The two-stack trick uses one observation: postorder is the reverse of "root, right, left". Produce root-right-left with an ordinary stack (like iterative preorder, but pushing left before right), push each popped node onto a second stack, and read that stack from top to bottom.
Example: [1, 2, 3, 4, 5, 6, 7] → [4, 5, 2, 6, 7, 3, 1].
vector<int> postorderTwoStacks(TreeNode* root);
| Input (level order) | Output | Explanation |
|---|---|---|
[1, 2, 3, 4, 5, 6, 7] | [4, 5, 2, 6, 7, 3, 1] | |
[1, null, 2, 3] | [3, 2, 1] | |
[1, 2, null, 3] | [3, 2, 1] | |
[1] | [1] | |
[] | [] |
(Confirm: no recursion; the output equals recursive postorder.)
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