Last active
May 5, 2022 19:45
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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