DSA interview question
A memory-starved embedded device must traverse a large binary tree in preorder, but it can't afford a stack or recursion: only a couple of pointers. Morris traversal borrows the tree's unused right pointers. Before descending into a node's left subtree, it links that subtree's rightmost node (the node's inorder predecessor) back to the node, which leaves a "thread" to return along. When the traversal comes back through the thread, it removes it, so the tree ends up exactly as it started.
Example: [1, 2, 3, 4, 5, 6, 7] → [1, 2, 4, 5, 3, 6, 7].
vector<int> morrisPreorder(TreeNode* root); // O(1) extra space; the tree is restored
| Input (level order) | Output | Explanation |
|---|---|---|
[1, 2, 3, 4, 5, 6, 7] | [1, 2, 4, 5, 3, 6, 7] | |
[1, null, 2, 3] | [1, 2, 3] | |
[1, 2, null, 3] | [1, 2, 3] | A left chain |
[5, 4, 6] | [5, 4, 6] | |
[] | [] |
(Confirm: no stack and no recursion; the tree must be unchanged afterwards.)
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