3

Consider the following tree structure.

    A
   / \
  B   C
 / \   \
D   E   F

In what order will the nodes be visited using a postorder, a preorder, and an inorder traversal?

Nick Meyer
  • 1,771
  • 1
  • 17
  • 29
user3500147
  • 125
  • 1
  • 11

1 Answers1

9

I find that it helps to think of postorder, preorder, and inorder as recursive algorithms.

Postorder traversal

Recursively, this is left, right, self. In other words, do the traversal for the left subtree, then do the traversal for the right subtree, and only then visit the current node. The base case would be when the node has no children.

For this example:

Answer: D, E, B, F, C, A

Explanation:

  1. Start at node A. Evaluate left subtree. At node B. Evaluate left subtree. At node D. No children -> visit D.
  2. Go back to B. Evaluate right subtree. At node E. No children -> visit E.
  3. Go back to B. Visit B.
  4. Go back to A. Evaluate right subtree. At node C. No left subtree, so evaluate right subtree. At node F. No children -> visit F.
  5. Go back to C. Visit C.
  6. Go back to A. Visit A

Preorder traversal

Recursively, this is self, left, right.

See if you can get the answer yourself using the logic of the postorder traversal.

Inorder traversal

Recursively, this is left, self, right.

See if you can get the answer yourself using the logic of the postorder traversal.

If you wish to check your work,

the Preorder traversal would be A, B, D, E, C, F and the Inorder traversal would be D, B, E, A, C, F.

Nick Meyer
  • 1,771
  • 1
  • 17
  • 29