DSA interview question
A leaderboard keeps scores in a binary search tree, and each new score must be inserted so that the tree stays a valid BST. The new key always ends up as a leaf. Walk down as if searching for it (left if it's smaller than the node, right if it's larger), and attach the new node at the first empty spot. No existing node moves, and the walk takes O(h).
Example: BST [4, 2, 7, 1, 3], insert 5 → [4, 2, 7, 1, 3, 5].
TreeNode* insertIntoBST(TreeNode* root, int val); // val is not already in the tree
Input (tree, val) | Output (level order) | Explanation |
|---|---|---|
([4, 2, 7, 1, 3], 5) | [4, 2, 7, 1, 3, 5] | 5 becomes 7's left child |
([40, 20, 60, 10, 30, 50, 70], 25) | [40, 20, 60, 10, 30, 50, 70, null, null, 25] | |
([4, 2, 7, 1, 3], 0) | [4, 2, 7, 1, 3, null, null, 0] | The new minimum |
([5], 6) | [5, null, 6] | |
([], 5) | [5] | Empty tree |
(Confirm: keys are distinct; any valid BST is accepted, and the leaf-insertion result is shown.)
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