CSC403: Printing: Print postfix with only one loop [8/10] Previous pageContentsNext page

    public void printPost () {
        Stack<Node> s = new Stack<>();
        s.push (root);

        Node prev = root;
        while (!s.isEmpty ()) {
            Node x = s.pop ();
            if (x == null) continue;
            if (x.right == prev || x.left == prev || (x.left == null && x.right == null)) {
                StdOut.print (x.key + " ");
                prev = x;
            } else {
                s.push (x);
                s.push (x.right);
                s.push (x.left);
            }
        }
        StdOut.println ();
    }

Print postfix with only one loop (from here and here)

Horror.

Previous pageContentsNext page