0

Consider this tree:

           7
         /    \
       /        \
      /          \
     1            9
    /  \         /  \
   0    3       8   10 
       / \
      2   5
         / \
        4   6

Inorder:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Preorder:

7, 1, 0, 3, 2, 5, 4, 6, 9, 8, 10

While doing Inorder traversal, the leftmost left node is first located and the traversal starts from there. But when it comes to Preorder the same logic(as in leftmost middle node) is not applied

In the above tree apart from the root 7, there is 1 and 9 which are both middle nodes. 1 being the leftmost middle node and 9 being the rightmost middle node. Going by the logic applied for above InOrder, the Preorder traversal should have begun from the node 1 which is the leftmost middle node, but its not so, why?

Why is it that in Inorder the traversal starts from the leftmost left node but the PreOrder traversal does not start from leftmost middle node?

Thanks, Chris.

ChrisOdney
  • 6,066
  • 10
  • 38
  • 48

2 Answers2

3

Preorder always puts the parent before its descendants (that is its definition), hence it has to start with the root. You could use the term "midllemost middle node" for the root if you like.

A typical use of preorder is the standard function notation: If you have something like

f(g(x, h(y, z)))

then this is a preorder notation of the following expression tree which uses the function name for inner nodes and the variables as leave nodes:

      f
      |
      g
     / \
    x   h
       / \
      y   z

On the other hand, the usual notation with operators like + and * uses an inorder:

a + b * c

is the inorder notation for

    +
   / \
  a   *
     / \
    b   c

if we use the standard mathematical precedence rules that * is binding stronger than +.

And writing expressions in reverse polish notation would be an example of postorder.

FrankPl
  • 13,205
  • 2
  • 14
  • 40
  • Is there a particular reason why the way it is? Putting the parent before the descendant. – ChrisOdney Aug 30 '13 at 05:34
  • 1
    @ChrisOdney I edited my answer to show some examples where the different orders are used in practice. These should show that preorder and inorder seem rather natural in ordinary mathematical or programming language use. – FrankPl Aug 30 '13 at 07:35
1

Inorder: Traverse Left subtree; Visit Current Node; Traverse Right subtree;

Preorder: Visit Current Node; Traverse Left subtree; Traverse Right subtree;

Postorder: Traverse Left subtree; Traverse Right subtree; Visit Current Node;

Note that you'll never have the same node in Inorder and Preorder unless the left subtree is missing.

However you can have the same node in Inorder and PostOrder representations if there is a left subtree.

user1952500
  • 6,611
  • 3
  • 24
  • 37