原题链接在这里:https://leetcode.com/problems/binary-search-tree-iterator/
AC Java:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Stack<TreeNode> stk = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
while(root != null){
stk.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stk.empty(); //error
}
/** @return the next smallest number */
public int next() {
TreeNode tn = stk.pop();
int res = tn.val;
if(tn.right != null){
tn = tn.right;
while(tn != null){
stk.push(tn);
tn = tn.left;
}
}
return res;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/

本文介绍了一种实现二叉搜索树迭代器的方法,通过使用栈来存储节点,可以有效地遍历二叉搜索树的所有元素,并按升序返回每个元素的值。此方法能够实现next和hasNext两个核心功能。
814

被折叠的 条评论
为什么被折叠?



