File tree 1 file changed +55
-0
lines changed
1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/binary-search-tree-iterator/
3
+ */
4
+
5
+ /**
6
+ * Definition for a binary tree node.
7
+ * public class TreeNode {
8
+ * public var val: Int
9
+ * public var left: TreeNode?
10
+ * public var right: TreeNode?
11
+ * public init() { self.val = 0; self.left = nil; self.right = nil; }
12
+ * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
13
+ * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
14
+ * self.val = val
15
+ * self.left = left
16
+ * self.right = right
17
+ * }
18
+ * }
19
+ */
20
+
21
+ class BSTIterator {
22
+ var cur : TreeNode ?
23
+ var stack : [ TreeNode ]
24
+
25
+ init ( _ root: TreeNode ? ) {
26
+ self . cur = root
27
+ self . stack = [ ]
28
+ }
29
+
30
+ func next( ) -> Int {
31
+ while cur != nil || !stack. isEmpty {
32
+ if cur != nil {
33
+ stack. append ( cur!)
34
+ cur = cur? . left
35
+ } else {
36
+ cur = stack. popLast ( )
37
+ let res = cur? . val ?? 0
38
+ cur = cur? . right
39
+ return res
40
+ }
41
+ }
42
+ return - 1
43
+ }
44
+
45
+ func hasNext( ) -> Bool {
46
+ cur != nil || !stack. isEmpty
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Your BSTIterator object will be instantiated and called as such:
52
+ * let obj = BSTIterator(root)
53
+ * let ret_1: Int = obj.next()
54
+ * let ret_2: Bool = obj.hasNext()
55
+ */
You can’t perform that action at this time.
0 commit comments