Iterative solution for non-tree graphs
After unsuccessfully experimenting with different solutions, let me add pseudocode for an iterative solution where you essentially recreate the function call stack space (that could overflow in a recursive version) in a stack variable.
All the state that you need to store is the vertex number and the number of neighbors already processed. This can be a tuple, a list, an object, whatever your language allows.
The advantage of this solution is that you don't get stack overflow, it also works for graphs having cycles and it's pretty robust. Getting the next neighbor is easy if you use an adjacency list or matrix.
This is pseudocode because it's easier to understand, and you wouldn't just copy code from SO, would you?
globals: isProcessed, preOrder, postOrder
depthFirstSearch()
set isProcessed to all false
for each vertex
if !isProcessed(vertex)
explore(vertex)
explore(root)
create stack
add (root, 0) to stack
visited = empty list
// a list of visited vertices e.g. for finding connected components
while stack is not empty
(vertex, processedNeighbors) ← pop from stack
if !isProcessed(vertex)
// previsit
add vertex to preOrder list
isProcessed(vertex) ← true
if processedNeighbors < number of vertex's neighbors
nextNeighborNumber ← processedNeighbors + 1
push (vertex, nextNeighborNumber) to stack
nextNeighbor ← 'nextNeighborNumber'th neighbor of vertex
if !isProcessed(nextNeighbor)
push (nextNeighbor, 0) to stack
else
// postvisit
add vertex to postOrder list