先序遍历:
public void preorderIterative() {
Stack<Node> stack = new Stack<Node>();
Node p = root;
if (p != null) {
stack.push(p);
while (!stack.empty()) {
p = stack.pop();
visit(p);
if (p.right != null)
stack.push(p.right);
if (p.left != null)
stack.push(p.left);
}
}
}
中序遍历:
public void inorderIterative() {
Stack<Node> stack = new Stack<Node>();
Node p = root;
while (p != null) {
while (p != null) {
if (p.right != null)
stack.push(p.right);
stack.push(p);
p = p.left;
}
p = stack.pop();
while (!stack.empty() && p.right == null) {
visit(p);
p = stack.pop();
}
visit(p);
if (!stack.empty())
p = stack.pop();
else
p = null;
}
}
后序遍历:
public void postorderIterative() {
Stack<Node> stack = new Stack<Node>();
Node p = root;
Node q = root;
while (p != null) {
while (p.left != null) {
stack.push(p);
p = p.left;
}
while (p != null && (p.right == null || p.right == q)) {
visit(p);
q = p;
if (stack.empty())
return;
p = stack.pop();
}
stack.push(p);
p = p.right;
}
}