
Untitled
By: a guest on
Jun 25th, 2012 | syntax:
None | size: 0.64 KB | hits: 14 | expires: Never
postorder using tail recursion
public static final <T> void postorder(Tree<T> root) {
Stack<Tree<T>> stack = new Stack<Tree<T>>();
Stack<Tree<T>> traversal = new Stack<Tree<T>>();
stack.push(root);
while (!stack.isEmpty()) {
Tree<T> node = stack.pop();
if (node.right != null)
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
traversal.push(node);
}
while (!traversal.isEmpty()) {
System.out.println(traversal.pop().value.toString());
}
}
public class StackElement<T> {
public Tree<T> node;
public int numTraversedChildren;
}