We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 2315484 commit 65d5e64Copy full SHA for 65d5e64
kth-smallest-element-in-a-bst/kimyoung.js
@@ -0,0 +1,15 @@
1
+var kthSmallest = function (root, k) {
2
+ const nums = [];
3
+ function helper(node) { // helper method to traverse the binary tree to map the node values to nums array
4
+ if (!node) return;
5
+ nums.push(node.val);
6
+ if (node.left) helper(node.left); // recursive call to left node if it exists
7
+ if (node.right) helper(node.right); // recursive call to right node if it exists
8
+ }
9
+ helper(root);
10
+ const sorted = nums.sort((a, b) => a - b); // sort the nums array
11
+ return sorted[k - 1]; // return kth smallest val
12
+};
13
+
14
+// space - O(n) - mapping node values into nums array
15
+// time - O(nlogn) - sort
0 commit comments