DS29.
DS29.
Three Algorithms
Preorder (NLR)
Process the root R.
Inorder (LNR)
Traverse the left subtree of R in Inorder.
Postorder (LRN)
Traverse the left subtree of R in Postorder.
B C
D E G H
F J K
L
Inorder: - D B F E A G C L J H K
Postorder: - D F E B G L J K H C A
Solve the Expression: -
(a – b) / ((c * d) + e)
/
- +
a b * e
c d
Preorder: - ?
Postorder: - ?
Traversal Algo using Stacks
PREORD(INFO, LEFT, RIGHT, ROOT)
A binary tree T is in memory. The algorithm does a Preorder traversal
of T, applying an operation PROCESS to each of its nodes. An array
STACK is used to temporarily hold the addresses of nodes.
1. [Initially push NULL onto STACK, & initialize PTR.] Set TOP := 1,
STACK[1] := NULL & PTR := ROOT.
2. Repeat Steps 3 to 5 while PTR != NULL.
3. Apply PROCESS to INFO[PTR].
4. [Right Child?] If RIGHT[PTR] != NULL, then: [Push on STACK.]
Set TOP := TOP + 1, & STACK[TOP] := RIGHT[PTR]. [End of
If structure.]
5. [Left Child?] If LEFT[PTR] != NULL, then: Set PTR := LEFT[PTR].
Else: [Pop from STACK.] Set PTR := STACK[TOP] & TOP := TOP
+ 1. [END OF If structure.] [End of Step 2 loop.]
6. Exit.
Example: -
STACK: - Φ A
PTR : = A
B C
D E F
G H
K
Preorder: - A B D G H K C E F
INORD(INFO, LEFT, RIGHT, ROOT)
A binary tree T is in memory. The algorithm does a Inorder traversal
of T, applying an operation PROCESS to each of its nodes. An
array STACK is used to temporarily hold the addresses of nodes.
1. [Initially push NULL onto STACK, & initialize PTR.]
Set TOP := 1, STACK[1] := NULL & PTR := ROOT.
2. Repeat while PTR != NULL: [Pushes left-most path onto stack.]
(a) Set TOP := TOP + 1, & STACK[TOP] := PTR. [Saves node.]
(b) Set PTR := LEFT[PTR]. [Updates PTR.]
[End of loop.]
3. Set PTR := STACK[TOP] & TOP := TOP - 1. [Pops nodes.]
4. Repeat Steps 5 to 7 while PTR != NULL: [Backtracking.]
5. Apply PROCESS to INFO[PTR].
6. [Right Child?] If RIGHT[PTR] != NULL, then:
(a) Set PTR := RIGHT[PTR].
(b) Go to Step 3.
[End of If structure.]
7. Set PTR := STACK[TOP] & TOP := TOP - 1. [Pops nodes.]
[End of Step 4 loop.]
8. Exit.
Example: -
STACK: - Φ A
PTR : = A
B C
D E
G H
K L M
Inorder: - K G D L H M B A E C
Thank You!!!