Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created July 30, 2022 14:13
Show Gist options
  • Save CarlaTeo/586d03dddd1ab580c3ffb25c5e9e2180 to your computer and use it in GitHub Desktop.
Save CarlaTeo/586d03dddd1ab580c3ffb25c5e9e2180 to your computer and use it in GitHub Desktop.
[JS] Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
** https://leetcode.com/problems/kth-smallest-element-in-a-bst/
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
// 1<= k <=n
// root not null
const kthSmallest = function(root, k) {
const sortedValuesGen = inOrder(root);
let kthSmallest;
while(k) {
kthSmallest = sortedValuesGen.next();
k--;
}
return kthSmallest.value;
};
function* inOrder(node) {
if(node.left) yield * inOrder(node.left);
yield node.val
if(node.right) yield * inOrder(node.right);
// // non-recursive inorder traversal
// const stack = [null];
// while(stack.length) {
// while(node) {
// stack.push(node);
// node = node.left;
// }
// const cur = stack.pop();
// if(cur) yield cur.val;
// if(cur.right) node = cur.right;
// else node = null;
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment