原题链接:173. Binary Search Tree Iterator
【思路-Java】中序遍历非递归实现
我们知道二叉搜索树当前节点值总是大于左子树上的任一节点值,总是大于右子树上的任一节点值。要从小到大取出该节点,我们可以采用二叉树的中序遍历,该思路借用一个栈来实现,如果对二叉树的中序遍历思路不是很清晰的,可以参考我的另一篇博文:leetcode 94. Binary Tree Inorder Traversal-中序遍历|递归|非递归
public class BSTIterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
while(root != null) {
stack.add(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode temp = stack.pop();
int val = temp.val;
if(temp.right != null) {
temp = temp.right;
while (temp != null) {
stack.add(temp);
temp = temp.left;
}
}
return val;
}
}
61 / 61
test cases passed. Runtime: 6 ms Your runtime beats 78.97% of javasubmissions.
【思路2-Java】
如果我们打破常规,不用栈来实现,那么我们就需要变换策略,需要申请几枚指针:
该思路就是借助指针,逐一将最左端的点加到 root 指针的右边
public class BSTIterator {
TreeNode root = new TreeNode(0);
public BSTIterator(TreeNode root) {
this.root.right = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return root.right != null;
}
/** @return the next smallest number */
public int next() {
TreeNode next = root.right;
if (next.left == null) {
root = next;
return next.val;
}
TreeNode right = root.right;
TreeNode parent = root;
while(next.left != null) {
parent = next;
next = next.left;
}
parent.left = next.right;
root.right = next;
next.right = right;
root = root.right;
return root.val;
}
}
61 / 61
test cases passed. Runtime: 5 ms Your runtime beats 94.32% of javasubmissions.