Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1203 from razer96/230-Kth-Smallest-Ele…
Browse files Browse the repository at this point in the history
…ment-in-a-BST.go

230. Kth Smallest Element in a BST go solution.go
  • Loading branch information
dissesmac authored Sep 30, 2022
2 parents 07eef8d + 0f3d0d7 commit 2f07dbd
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions go/230-Kth-Smallest-Element-in-a-BST.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
func kthSmallest(root *TreeNode, k int) int {
stack := make([]*TreeNode, 0, k)

for {
for root != nil {
stack = append(stack, root)
root = root.Left
}

root = stack[len(stack) - 1]
stack = stack[:len(stack) - 1]

k--
if k == 0 {
return root.Val
}

root = root.Right
}

return -1
}

0 comments on commit 2f07dbd

Please sign in to comment.