Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Last active May 5, 2022 19:45
Show Gist options
  • Save Turskyi/57932a894c9e5806c04e121883233a1a to your computer and use it in GitHub Desktop.
Save Turskyi/57932a894c9e5806c04e121883233a1a to your computer and use it in GitHub Desktop.
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.
/*
Given the reference to a binary search tree, return the kth the smallest value in the tree.
* */
fun kthSmallest(root: TreeNode?, k: Int): Int {
val nodeQue: Queue<TreeNode?> = LinkedList<TreeNode?>()
nodeQue.offer(root)
val values: HashSet<Int> = HashSet()
while (nodeQue.isNotEmpty()) {
val currentNode: TreeNode? = nodeQue.poll()
if (currentNode != null) {
values.add(currentNode.`val`)
}
if (currentNode?.left != null) {
nodeQue.offer(currentNode.left)
}
if (currentNode?.right != null) {
nodeQue.offer(currentNode.right)
}
}
return values.elementAt(k - 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment