Skip to content

Commit 65d5e64

Browse files
committed
Kth Smallest Element in a BST solution
1 parent 2315484 commit 65d5e64

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)