-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path173.swift
51 lines (45 loc) · 1.26 KB
/
173.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
42
43
44
45
46
47
48
49
50
51
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class BSTIterator {
private var nodes = [TreeNode]()
private func pushLeftChildren(_ node: TreeNode?) {
var node = node
while node != nil {
nodes.append(node!)
node = node?.left
}
}
init(_ root: TreeNode?) {
guard let root = root else { return }
pushLeftChildren(root)
}
func next() -> Int {
let result = nodes.removeLast()
if let right = result.right {
pushLeftChildren(right)
}
return result.val
}
func hasNext() -> Bool {
return !nodes.isEmpty
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* let obj = BSTIterator(root)
* let ret_1: Int = obj.next()
* let ret_2: Bool = obj.hasNext()
*/