15

Given the directed graph below, how did we achieve the post-order traversal?

DFS

Visiting order in Pre-order traversal: 1 2 5 4 6 3

Visiting order in Post-order traversal: 4 6 5 2 1 3

enter image description here

displayName
  • 12,673
  • 7
  • 50
  • 70
33ted
  • 667
  • 1
  • 5
  • 14
  • 2
    I'm voting to close this question as off-topic because it is not a programming question. It appears to be a question about algorithm theory. – Raymond Chen Apr 07 '16 at 23:31
  • 6
    I'm voting to close this question as off-topic because it is not about programming. –  May 25 '16 at 04:09
  • 15
    How is an algorithm not programming? We'll not be able to discuss design patterns next. This close is wrong in my opinion. Vote to open. – Liam May 25 '16 at 10:30
  • 9
    @Liam, this may explain why there are so many buggy applications around: some programmers nowadays seem to consider algorithms as someone else's problem ;-) – Bruno May 25 '16 at 13:09
  • 1
    it is **too broad** as well as **no mcve**, multiple off-topics –  May 25 '16 at 13:58
  • 5
    @JarrodRoberson I think there' s exactly one correct answer so it's not too broad. MCVE is n/a to this question. Usually we require MCVEs for solving bugs in code. – djechlin May 25 '16 at 18:35
  • Is this a homework assignment? – Stefan May 26 '16 at 09:53
  • Are you sure about answer correctness for post-order?! –  Nov 11 '20 at 11:26

1 Answers1

21

Post-order DFS essentially has the following design:

  1. Visit the children;
  2. Visit myself;

Starting at 1, the nodes are explored in the following order:

1 -> 2 -> 5 -> 4(v) ->6(v) -> 5(v) -> 2(v) -> 1(v) -> 3(v)

Here (v) implies that the node is visited now after seeing that either none of its children are left unvisited or at least they are in the pipeline for visit. This explains why the traversal is 465213.

Probably, what bothers you is how we visited the node 3 because beginning from 1 there is no path to 3. The answer to that seems that after entire connected graph has been scanned, the traversal algorithm scans if there are any unscanned nodes left. So then it ends up visiting 3 at the end.

displayName
  • 12,673
  • 7
  • 50
  • 70