Skip to content

Commit 5b4f429

Browse files
committed
Feat: add an awesome code from leetcode
1 parent 0cac7f6 commit 5b4f429

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

kth-smallest-element-in-a-bst/HC-kang.ts

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,60 @@ function kthSmallest(root: TreeNode | null, k: number): number {
4848
inorder(root, arr);
4949
return arr[k - 1];
5050
}
51+
52+
/**
53+
* Awesome solution from leetcode
54+
*/
55+
function kthSmallest(root: TreeNode | null, k: number): number {
56+
/*
57+
define. return the kth smallest value in a BST.
58+
assess. smallest value can be 0. At least k nodes, which can be at its smallest, 1.
59+
approach. DFS with backtracking. Traverse down the left edges until we hit null. if k is 1, return that value. Else, backtrack, go right, then try to go left again. Use a stack.
60+
*/
61+
62+
// let currentRank = 0;
63+
64+
// let stack = [];
65+
66+
// let currentNode = root;
67+
68+
// while (currentNode || stack.length > 0) {
69+
// while (currentNode) {
70+
// stack.push(currentNode);
71+
72+
// currentNode = currentNode.left;
73+
// }
74+
75+
// currentNode = stack.pop();
76+
77+
// currentRank++;
78+
79+
// if (currentRank === k) return currentNode.val;
80+
81+
// currentNode = currentNode.right;
82+
// }
83+
84+
const stack = [];
85+
86+
let currentRank = 0;
87+
88+
let currentNode = root;
89+
90+
while (currentNode || stack.length > 0) {
91+
92+
while (currentNode) {
93+
stack.push(currentNode);
94+
95+
currentNode = currentNode.left;
96+
}
97+
98+
currentNode = stack.pop();
99+
100+
currentRank++;
101+
102+
if (currentRank === k) return currentNode.val;
103+
104+
currentNode = currentNode.right;
105+
}
106+
107+
};

0 commit comments

Comments
 (0)