2019.11.16 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
数据结构题。
要求实现一个二叉搜索树的迭代器,实际上依靠一个栈即可实现。构造迭代器时,从根节点遍历至最左结点(最小起始节点),并将左侧遍历的元素全部入栈。
每次访问next(),将栈顶元素出栈并返回,将其右子树的所有左侧结点入栈。
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.
实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
示例:
7
/ \
3 15
/ \
9 20
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false
import java.util.Stack;
/**
*
* 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.
* 实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
* 调用 next() 将返回二叉搜索树中的下一个最小的数。
*
*/
public class BinarySearchTreeIterator {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
TreeNode cur = root;
while(cur != null){
stack.push(cur);
cur = cur.left;
}
}
/** @return the next smallest number */
public int next() {
TreeNode node = stack.pop();
TreeNode cur = node;
cur = cur.right;
while(cur != null){
stack.push(cur);
cur = cur.left;
}
return node.val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#