-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy path173_Binary_Search_Tree_Iterator.py
More file actions
76 lines (65 loc) · 1.79 KB
/
Copy path173_Binary_Search_Tree_Iterator.py
File metadata and controls
76 lines (65 loc) · 1.79 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Approach 1: https://tinyurl.com/smu9ku3
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.nodesSorted = []
self.nextIndex = 0
self.__inorder(root)
def __inorder(self, root):
if not root:
return
self.__inorder(root.left)
self.nodesSorted.append(root.val)
self.__inorder(root.right)
def next(self):
"""
@return the next smallest number
:rtype: int
"""
value = self.nodesSorted[self.nextIndex]
self.nextIndex += 1
return value
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return self.nextIndex < len(self.nodesSorted)
# Approach 2: https://tinyurl.com/smu9ku3
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.__leftMostInorder(root)
def __leftMostInorder(self, root):
curentStack = self.stack
while root:
curentStack.append(root)
root = root.left
def next(self):
"""
@return the next smallest number
:rtype: int
"""
curentStack = self.stack
topMostNode = curentStack.pop()
if topMostNode.right:
self.__leftMostInorder(topMostNode.right)
return topMostNode.val
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
curentStack = self.stack
return len(curentStack) > 0