Skip to content

Instantly share code, notes, and snippets.

@volkanbicer
Created November 10, 2017 04:43
Show Gist options
  • Save volkanbicer/1d4e5476f93cadbdbcff5903fa90eb5d to your computer and use it in GitHub Desktop.
Save volkanbicer/1d4e5476f93cadbdbcff5903fa90eb5d to your computer and use it in GitHub Desktop.
Kth Smallest Element in a BST
func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int {
guard let _ = root else {
return -1
}
var count = 0
var stack = [TreeNode]()
var root = root
while !stack.isEmpty || root != nil {
while root != nil {
stack.append(root!)
root = root!.left
}
root = stack.removeLast()
count += 1
if count == k {
break
}
root = root!.right
}
return root!.val
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment