1 class BSTIterator:
 2     def __init__(self, root: TreeNode):
 3         self.lists = []
 4         self.idx = 0
 5         self.size = 0
 6         self.inOrder(root)
 7         
 8     def inOrder(self,root):
 9         if root != None:
10             if root.left != None:
11                 self.inOrder(root.left)
12             self.lists.append(root.val)
13             self.size += 1
14             if root.right != None:
15                 self.inOrder(root.right)
16 
17     def next(self) -> int:
18         """
19         @return the next smallest number
20         """
21         if self.hasNext():
22             v = self.lists[self.idx]
23             self.idx += 1
24             return v
25         else:
26             return -1
27         
28     def hasNext(self) -> bool:
29         """
30         @return whether we have a next smallest number
31         """
32         return self.idx < self.size

 

posted on 2019-12-11 10:14  Sempron2800+  阅读(153)  评论(0编辑  收藏  举报