DSA interview question
A compiler dumps expression trees as their inorder and postorder sequences (all node IDs distinct), and a debugger must rebuild the tree. Postorder lists the root last, so read postorder from the end. Each value taken is the root of the current inorder range, and its position in inorder splits the range into left and right parts. Reading backwards, postorder gives root, then the right subtree, then the left, so the right subtree must be built first.
Example: inorder [9, 3, 15, 20, 7], postorder [9, 15, 7, 20, 3] → [3, 9, 20, null, null, 15, 7].
TreeNode* buildTree(const vector<int>& inorder, const vector<int>& postorder);
Input (inorder, postorder) | Output (level order) | Explanation |
|---|---|---|
([9, 3, 15, 20, 7], [9, 15, 7, 20, 3]) | [3, 9, 20, null, null, 15, 7] | |
([4, 2, 5, 1, 6, 3, 7], [4, 5, 2, 6, 7, 3, 1]) | [1, 2, 3, 4, 5, 6, 7] | |
([2, 1], [2, 1]) | [1, 2] | 2 is a left child |
([1, 2], [2, 1]) | [1, null, 2] | 2 is a right child |
([-1], [-1]) | [-1] |
(Confirm: values are distinct and both arrays describe the same tree.)
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