-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0173-binary-search-tree-iterator.swift
55 lines (49 loc) · 1.34 KB
/
0173-binary-search-tree-iterator.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
52
53
54
55
/**
* Question Link: https://leetcode.com/problems/binary-search-tree-iterator/
*/
/**
* 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 {
var cur: TreeNode?
var stack: [TreeNode]
init(_ root: TreeNode?) {
self.cur = root
self.stack = []
}
func next() -> Int {
while cur != nil || !stack.isEmpty {
if cur != nil {
stack.append(cur!)
cur = cur?.left
} else {
cur = stack.popLast()
let res = cur?.val ?? 0
cur = cur?.right
return res
}
}
return -1
}
func hasNext() -> Bool {
cur != nil || !stack.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()
*/