-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path173.binary-search-tree-iterator.py
53 lines (45 loc) · 1.11 KB
/
173.binary-search-tree-iterator.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
#
# @lc app=leetcode id=173 lang=python
#
# [173] Binary Search Tree Iterator
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
while root:
self.stack.append(root)
root = root.left
def next(self):
"""
@return the next smallest number
:rtype: int
"""
node = self.stack.pop()
val = node.val
if node.right:
node = node.right
while node:
self.stack.append(node)
node = node.left
return val
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return len(self.stack) != 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
# @lc code=end