题目概述
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next()
will return the next smallest number in the BST.
Example:
1 | BSTIterator iterator = new BSTIterator(root); |
Note:
next()
andhasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.- You may assume that
next()
call will always be valid, that is, there will be at least a next smallest number in the BST whennext()
is called.
这题我使用了一个DFS来遍历BST,并且把按顺序把树的节点存到了self.nodes的list中。这个类同时还保存了一个当前对象在self.nodes的索引值,如果使用了next方法,就把这个索引值加一,hasnext则判断这个索引值和self.nodes的长度的关系
代码实现
1 | class BSTIterator: |