Simplest iterative algorithm Post order traversal

public class POIterateSimple {
public static void main(String[] args) {
    pfIterate(PFIterate.NODE);
}
private static void pfIterate(Node root) {
    Node prev = null;
    Stack stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        root = stack.pop();
        if (root.left == null && root.right == null) {
            System.out.print(root.data + " ");
            prev = root;
        } else if (prev == root.left || prev == root.right) {
            System.out.print(root.data + " ");
            prev = root;
        } else {
            stack.push(root);
            if (root.right != null)
                stack.push(root.right);
            if (root.left != null)
                stack.push(root.left);
        }
    }
 }
}

Comments

Popular posts from this blog

java.net.SocketException: Connection reset

Hide empty last column from Table/Tree Viewer

Spring: implements interface not working in @Controller