Created
November 10, 2017 04:43
-
-
Save volkanbicer/1d4e5476f93cadbdbcff5903fa90eb5d to your computer and use it in GitHub Desktop.
Kth Smallest Element in a BST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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