Skip to content

Commit 2f07dbd

Browse files
authored
Merge pull request neetcode-gh#1203 from razer96/230-Kth-Smallest-Element-in-a-BST.go
230. Kth Smallest Element in a BST go solution.go
2 parents 07eef8d + 0f3d0d7 commit 2f07dbd

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
func kthSmallest(root *TreeNode, k int) int {
2+
stack := make([]*TreeNode, 0, k)
3+
4+
for {
5+
for root != nil {
6+
stack = append(stack, root)
7+
root = root.Left
8+
}
9+
10+
root = stack[len(stack) - 1]
11+
stack = stack[:len(stack) - 1]
12+
13+
k--
14+
if k == 0 {
15+
return root.Val
16+
}
17+
18+
root = root.Right
19+
}
20+
21+
return -1
22+
}

0 commit comments

Comments
 (0)