173. Binary Search Tree Iterator
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
int next() Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
此方法不用将所有节点一次性入栈,而是在获得next时更新栈内的节点,因此更省时间。
将根节点的所有左子节点入栈,此时栈顶为最小值。
next方法:返回当前的栈顶节点。如果栈顶节点存在右子节点,则将其所有的左子节点入栈。
hasNext方法:返回栈是否为空的非值。
1 | /** |
DFS搜索,中序搜索,从右子节点至左子节点,先将所有元素入栈。
next方法:挤出栈顶并返回。
hasNext方法: 返回栈是否为空的非值。
1 | /** |