-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path173. 二叉搜索树迭代器
More file actions
41 lines (33 loc) · 1006 Bytes
/
173. 二叉搜索树迭代器
File metadata and controls
41 lines (33 loc) · 1006 Bytes
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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.result=[]
self.index=0
queue=[root]
if not root:
self.length=0
return
a=lambda root: [] if not root else a(root.left)+[root.val]+a(root.right)
# 中序遍历获得已经排序好的list
self.result=a(root)
self.length=len(self.result)
def next(self) -> int:
"""
@return the next smallest number
"""
self.index+=1
return self.result[self.index-1]
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return self.index<=self.length-1
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()