First, let's write a program to inorder traverse BST using iterative way.
public void inorder(Node node) {
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || node != null) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
visit(node);
node = node.right;
}
}
class InorderIterator {
Stack<Node> stack;
Node next;
Node node;
InorderIterator(Node root) {
if (root== null) {
throw new NullPointerException();
}
node = root;
stack = new Stack<Node>();
while (node != null) {
stack.push(node);
node = node.left;
}
next = stack.pop();
node = node.right;
}
Node next() {
Node temp = next;
if (stack.isEmpty() && node == null) {
thrwo new NoSuchElementException();
} else {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
next = node;
node = node.right;
}
return temp;
}
}
public Node next(Node node) {
if (node.right != null) {
return leftMost(node.right);
} else {
while (node.p != null && node == node.p.right) {
node = node.p;
}
return node.p;
}
}
public Node next(Node root, Node node) {
if (node.right != null) {
return leftMost(node.right);
} else {
Node next = null;
while (root != node) {
if (node.val <= root.val) {
next = root;
root = root.left;
} else {
root = root.right;
}
}
return next;
}
}
没有评论:
发表评论