-
Notifications
You must be signed in to change notification settings - Fork 886
/
KthSmallestElementBST.swift
41 lines (36 loc) · 1.12 KB
/
KthSmallestElementBST.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Question Link: https://leetcode.com/problems/kth-smallest-element-in-a-bst/
* Primary idea: use stack to do inorder traverse and track k to find answer
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class KthSmallestElementBST {
func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int {
var stack = [TreeNode](), currentNode = root, k = k
while !stack.isEmpty || currentNode != nil {
if currentNode != nil {
stack.append(currentNode!)
currentNode = currentNode!.left
} else {
let node = stack.removeLast()
k -= 1
if k == 0 {
return node.val
}
currentNode = node.right
}
}
return -1
}
}