Skip to content

Commit ae2c1e4

Browse files
authored
Update Binary Search Tree Iterator.py
1 parent 803ef8d commit ae2c1e4

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

Binary Search Tree Iterator.py

+19-17
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,7 @@
33
44
Calling next() will return the next smallest number in the BST.
55
6-
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
7-
8-
Credits:
9-
Special thanks to @ts for adding this problem and creating all test cases.
6+
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
107
'''
118

129
# Definition for a binary tree node
@@ -16,35 +13,40 @@
1613
# self.left = None
1714
# self.right = None
1815

16+
# Definition for a binary tree node
17+
# class TreeNode(object):
18+
# def __init__(self, x):
19+
# self.val = x
20+
# self.left = None
21+
# self.right = None
22+
1923
class BSTIterator(object):
2024
def __init__(self, root):
2125
"""
2226
:type root: TreeNode
2327
"""
2428
self.stack = []
25-
self.cur = root
26-
29+
self.push(root)
2730

31+
def push(self, node):
32+
while node:
33+
self.stack.append(node)
34+
node = node.left
35+
2836
def hasNext(self):
2937
"""
3038
:rtype: bool
3139
"""
32-
return self.stack or self.cur
40+
return len(self.stack) > 0
3341

3442
def next(self):
3543
"""
3644
:rtype: int
3745
"""
38-
while self.cur:
39-
self.stack.append(self.cur)
40-
self.cur = self.cur.left
41-
42-
self.cur = self.stack.pop()
43-
node = self.cur
44-
self.cur = self.cur.right
45-
46-
return node.val
47-
46+
top = self.stack.pop()
47+
self.push(top.right)
48+
return top.val
49+
4850
# Your BSTIterator will be called like this:
4951
# i, v = BSTIterator(root), []
5052
# while i.hasNext(): v.append(i.next())

0 commit comments

Comments
 (0)