Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created April 17, 2023 16:25
Show Gist options
  • Select an option

  • Save optimistiks/2b15b793326aca68a74ab8f4b06f310b to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/2b15b793326aca68a74ab8f4b06f310b to your computer and use it in GitHub Desktop.
Given the root node of a binary search tree and an integer value k, return the kth smallest value from all the nodes of the tree.
export function kthSmallestElement(root, k) {
const items = []
// traverse tree in order, creating a sorted arrat
inorder(root, (value) => items.push(value))
// grab k-1th item as a result
return items[k - 1];
}
function inorder(root, callback) {
const stack = [];
let current = root;
while (current || stack.length > 0) {
while (current) {
stack.push(current)
current = current.left
}
current = stack.pop()
callback(current.data)
current = current.right
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment