Search⌘ K
AI Features

Preorder and Postorder

Explore how to implement preorder and postorder traversals on directed graphs using depth-first search in Java. Learn the timing of vertex visits, classify edges, and understand recursion stacks to deepen your graph algorithm knowledge.

Hopefully, you are already familiar with the preorder and postorder traversals of rooted trees, both of which can be computed using depth-first search. Similar traversal orders can be defined for arbitrary directed graphs—even if they are disconnected—by passing around a counter, as shown below. Equivalently, we can use our generic depth-first-search algorithm with the following subroutines PreprocessPreprocess, PreVisitPreVisit, and PostVisitPostVisit.

Algorithm


Preprocess(G):clock0{\color{Blue} \underline{Preprocess(G):}} \\ \hspace{0.4cm} {\color{Blue} clock \rightarrow 0 }

PreVisit(v):clockclock+1v.preclock{\color{Red} \underline{PreVisit(v):}} \\ \hspace{0.4cm} {\color{Red} clock ← clock + 1 } \\ \hspace{0.4cm} {\color{Red} v.pre ← clock }

PostVisit(v):clockclock+1v.postclock{\color{Green} \underline{PostVisit(v):}} \\ \hspace{0.4cm} {\color{Green} clock ← clock + 1 } \\ \hspace{0.4cm} {\color{Green} v.post ← clock }

DFSAll(G):clock0for all vertices vunmark vfor all vertices vif v is unmarkedclockDFS(v,clock)\underline{DFSAll(G):} \\ \hspace{0.4cm} {\color{Blue} clock \leftarrow 0 } \\ \hspace{0.4cm} for\space all\space vertices\space v \\ \hspace{1cm} unmark\space v \\ \hspace{0.4cm} for\space all\space vertices\space v \\ \hspace{1cm} if\space v\space is\space unmarked \\ \hspace{1.7cm} clock ← DFS(v, clock)

DFS(v,clock):mark vclockclock+1;v.preclockfor each edge vwif w is unmarkedw.parentvclockDFS(w,clock)clockclock+1;v.postclo ...