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.
Note: next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
题目大意:实现二分搜索树的迭代器。
思路:由于二分搜索树的中序遍历是从小到大顺序排列的数列,只需要采用一个栈存储遍历的数据,然后当迭代器需要获得下一个元素的时候就将栈里面的元素弹出即可。
public class BSTIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>(); // initialize the stack
stackHelper(root);
}
public void stackHelper(TreeNode root){
if (root == null) return;
stackHelper(root.right);
stack.push(root);
stackHelper(root.left);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
return stack.pop().val;
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。