Wrong Answer occured when I submitted my solution for input below:
["BSTIterator","hasNext","next","hasNext"]
[[[1]],[null],[null],[null]]
The wrong answer is "[null,true,3,true]"
However, when I tested the given input, it got the right answer, which is "[null,true,1,false]"
Does anyone know the reason for inconsistent answers of same input?
# 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):
res = []
index = 0
def __init__(self, root):
"""
:type root: TreeNode
"""
stack = []
while True:
while root:
stack.append(root)
root = root.left
if not stack:
break
root = stack.pop()
self.res.append(root.val)
root = root.right
def next(self):
"""
@return the next smallest number
:rtype: int
"""
if self.hasNext():
self.index += 1
return self.res[self.index - 1]
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
if self.index != len(self.res):
return True
return False
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()