Kth Smallest Element in a BST - LeetCode 230 - JavaScript

preview_player
Показать описание


Step by step walk through of the solution to the popular Meta coding interview question, Kth Smallest Element in a BST.

LeetCode 230

0:00 Intro
0:27 Explanation
2:37 Code

JavaScript

#softwareengineering #javascript #leetcode
Рекомендации по теме
Комментарии
Автор

This could be further simplified. Note that w/ BST, inORder returns us a sorted result.
So after the dfs, we can simply return res[k-1].

function test(root, k) {
let res = []

function rec(node) {
if (!node) return

rec(node.left)
res.push(node.val)
rec(node.right)
}

rec(root)


//-1 to offset for zerobased indexing
return res[k - 1]
}

jritzeku
Автор

thanks i understood because this video

copterbuddy
Автор

Thank you for explaining what the question was actually asking it is confusing at first

OGKix
Автор

hey,
how about just returning arr[k-1] instead of writing findKth function

var kthSmallest = function(root, k) {
const arr = [];
inOrder(root, arr);

return arr[k-1]
};

function inOrder(root, arr){
if(!root) return null

inOrder(root.left, arr)
arr.push(root.val)
inOrder(root.right, arr)
}



btw, im following your blind 75 playlist, loving it, its precise and to the point explanation

love from india

shantanusutar
Автор

Can we just pass a variable in the recursion to keep track at what node we are at, then when we reach node #k we return it

brianspinos
Автор

Good explanation, but I feel like this is too verbose when it can be accomplished with less code just defining an inner dfs functions
const kthSmallest = (root, k) => {
const stack = [];

const dfs = (node) => {
if(!node) return;

dfs(node.left);
stack.push(node.val);
dfs(node.right);
}

dfs(root)
return stack[k - 1];
};

mxc_clips
welcome to shbcf.ru