-
Notifications
You must be signed in to change notification settings - Fork 886
/
BinarySearchTreeIterator.swift
58 lines (47 loc) · 1.33 KB
/
BinarySearchTreeIterator.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
56
57
58
/**
* Question Link: https://leetcode.com/problems/binary-search-tree-iterator/
* Primary idea: In order iteration using a stack.
* 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 BSTIterator {
var stack: [TreeNode]
init(_ root: TreeNode?) {
stack = [TreeNode]()
loadAllLeftToStack(from: root)
}
/** @return the next smallest number */
func next() -> Int {
let node = stack.removeLast()
loadAllLeftToStack(from: node.right)
return node.val
}
/** @return whether we have a next smallest number */
func hasNext() -> Bool {
return !stack.isEmpty
}
private func loadAllLeftToStack(from root: TreeNode?) {
var node = root
while let current = node {
stack.append(current)
node = current.left
}
}
}
/**
* 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()
*/