A friend was asked this a algorithm question about in order travesing a BST. And find a node based on certain criteria.
It was similar to Find k-th smallest element in BST, and he used a recurisve approach to write the solution, something like this
var kthSmallest = function(root, k) {
if (!root) return null;
let inOrderArray =[];
function inOrder(node){
if(!node) return;
inOrder(node.left);
inOrderArray.push(node.val)
inOrder(node.right);
}
inOrder(root);
return inOrderArray[k-1]
};However the interviewer asked him to optimize based on this recurisve approach, i.e. once we found the node, we stop the execution of the function and returrn immediatly. My friend and I failed to find the optimized solution.
Can someone please help me analyze this question and come up with some ideas?