DSA interview question
The same build system from before now runs on a device with little memory, so the second stack (which holds every node) is too expensive. With one stack, the challenge is knowing, when you look at a node on top of the stack, whether its right subtree has already been processed. Track the last node recorded. A node on top may be recorded if it has no right child or if its right child was the last node recorded. Otherwise, go and process its right subtree first.
Example: [1, 2, 3, 4, 5, null, 8, null, null, 6, 7, 9] → [4, 6, 7, 5, 2, 9, 8, 3, 1].
vector<int> postorderOneStack(TreeNode* root);
| Input (level order) | Output | Explanation |
|---|---|---|
[1, 2, 3, 4, 5, null, 8, null, null, 6, 7, 9] | [4, 6, 7, 5, 2, 9, 8, 3, 1] | |
[2, 1, 3] | [1, 3, 2] | |
[1, null, 2, null, 3] | [3, 2, 1] | A right chain: the tricky case |
[1] | [1] | |
[] | [] |
(Confirm: one explicit stack plus O(1) extra pointers; the output equals recursive postorder.)
cur and last.)last tell you?"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