forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-search-tree-iterator-ii.py
57 lines (47 loc) · 1.22 KB
/
binary-search-tree-iterator-ii.py
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
# Time: O(1), amortized
# Space: O(h)
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.__stk = []
self.__traversalLeft(root)
self.__vals = []
self.__pos = -1
def hasNext(self):
"""
:rtype: bool
"""
return self.__pos+1 != len(self.__vals) or self.__stk
def next(self):
"""
:rtype: int
"""
self.__pos += 1
if self.__pos == len(self.__vals):
node = self.__stk.pop()
self.__traversalLeft(node.right)
self.__vals.append(node.val)
return self.__vals[self.__pos]
def hasPrev(self):
"""
:rtype: bool
"""
return self.__pos-1 >= 0
def prev(self):
"""
:rtype: int
"""
self.__pos -= 1
return self.__vals[self.__pos]
def __traversalLeft(self, node):
while node is not None:
self.__stk.append(node)
node = node.left