Lec-14 Traversing A Binary Tree
Lec-14 Traversing A Binary Tree
1
Traversing Binary Tree
There are 3 ways of traversing a binary tree T having root R.
1. Preorder Traversing
• Steps:
(a) Process the root R
(b) Traverse the left subtree of R in preorder.
(c) Traverse the right subtree of R in preorder.
• Example: A
B C
Preorder Traversal of T
D E F G
A, B, D, H, E, C, F, I, J, G
H I J
B C
Inorder Traversal of T
D E F G D, H, B, E, A, I, F, J, C, G
H I J
3
3. Postorder Traversing
• Steps:
(a) Traverse the left subtree of R in postorder.
(b) Traverse the right subtree of R in postorder.
(c) Traverse the root R.
• Example:
A
B C
Postorder Traversal of T
D E F G H, D, E, B, I, J, F, G, C, A
H I J
4
Traversal Algorithms Using Stacks
(6) Exit.
5
Example: A
B C
D E F G
H I J
Figure: Binary Tree T
Preorder Traversal of T: A, B, D, H, E, C, F, I, J, G
7
2. Inorder Traversal Using Stack
Algorithm: Inorder_Traverse(Tree, Root, Stack)
(8) Exit
8
Example: A
B C
D E F G
Inorder Traversal of T: D, H, B, E, A, I, F, J, C, G
10
Assignment
Write an algorithm that will traverse a binary tree in postorder traversal using stack. Discuss
11
END!!!
10/23/08 12