Created
April 17, 2023 16:25
-
-
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.
This file contains hidden or 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
| 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