Saturday, March 12, 2011

Iterative Binary Tree Traversals

Iterative PreOrder traversal of a Binary Tree:

private void preOrderIterative(Node node) {
Stack stack = new Stack();

while (node != null || !stack.isEmpty()) {
if (null == node) {
node = stack.pop();
}
System.out.print(node.data + " -> ");
if (node.right != null) {
stack.push(node.right);
}
node = node.left;
}
}

Iterative InOrder traversal of a Binary Tree:

private void inorderIterative(Node node) {
Stack stack = new Stack();
while (node != null || !stack.isEmpty()) {
if (null == node) {
node = stack.pop();
System.out.print(node.data + " -> ");
node = node.right;
}
if (node != null) {
stack.push(node);
node = node.left;
}
}
}

Iterative PostOrder traversal of a Binary Tree:

private void preorderIterative(Node node) {
Stack stack = new Stack();
while (node != null || !stack.isEmpty()) {
if (node == null) {
while (!stack.isEmpty() && (node == stack.peek().right)) {
node = stack.pop();
System.out.print(node.data + " -> ");
}
node = stack.isEmpty()? null : stack.peek().right;
}
if (node != null) {
stack.push(node);
node = node.left;
}
}
}

No comments:

Post a Comment