Skip to content

Commit 7268f40

Browse files
committed
Add kth-smallest-element-in-a-bst solution
1 parent 05e108e commit 7268f40

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// 🚀 Optimized Approach: Inorder Traversal (BST Property)
2+
// ✅ Time Complexity: O(n), n represents the number of nodes
3+
// ✅ Space Complexity: O(n), due to recursion stack (in the worst case, e.g., unbalanced tree)
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* function TreeNode(val, left, right) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
*/
13+
/**
14+
* @param {TreeNode} root
15+
* @param {number} k
16+
* @return {number}
17+
*/
18+
var kthSmallest = function (root, k) {
19+
// Correct Order in BST Inorder Traversal: 🌿 (left) → 🌟 (current) → 🌳 (right)
20+
// 🌿 Go Left (visit the smallest values first).
21+
// 🌟 Visit Current Node (increment count++).
22+
// 🌳 Go Right (visit larger values).
23+
24+
let count = 0;
25+
let result = null;
26+
27+
const inorder = (node) => {
28+
if (!node || result !== null) return; // If node is null or result is found, stop recursion
29+
30+
inorder(node.left);
31+
32+
count += 1; // Visit current node
33+
if (count === k) {
34+
result = node.val;
35+
return;
36+
}
37+
38+
inorder(node.right);
39+
};
40+
41+
inorder(root);
42+
43+
return result;
44+
};
45+
46+
47+
// 😊 My initial approach
48+
// 🐌This is not optimal for a BST, but it works.
49+
// ✅ Time Complexity: O(n * logn), n represents the number of nodes
50+
// ✅ Space Complexity: O(n)
51+
52+
/**
53+
* Definition for a binary tree node.
54+
* function TreeNode(val, left, right) {
55+
* this.val = (val===undefined ? 0 : val)
56+
* this.left = (left===undefined ? null : left)
57+
* this.right = (right===undefined ? null : right)
58+
* }
59+
*/
60+
/**
61+
* @param {TreeNode} root
62+
* @param {number} k
63+
* @return {number}
64+
*/
65+
// var kthSmallest = function (root, k) {
66+
// let arr = [];
67+
// const dfs = (node) => {
68+
// if (!node) return null;
69+
70+
// if (node.val !== undefined) {
71+
// arr.push(node.val);
72+
// dfs(node.left);
73+
// dfs(node.right);
74+
// }
75+
// };
76+
77+
// dfs(root);
78+
79+
// arr.sort((a, b) => a - b);
80+
81+
// return arr[k - 1];
82+
// };

0 commit comments

Comments
 (0)