Unit 6: BST Traversal
CC4 – Data Structures and Algorithms
Instructor: Don Harl C. Malabanan
Introduction to Traversal
What is a traversal in BST?
• How a computer interprets a binary search tree.
• Three (3) types:
• Preorder
• Inorder
• Postorder
Binary Search Tree Preorder
• Used to get the prefix expressions of the binary search tree
• Used by programs that have a better time complexity with prefixes
• Steps:
1. Print the root
2. Traverse to the left subtree (if it exists) and print. Repeat until leaf node
reached
3. Go up one parent node and traverse right subtree (if it exists). Go to step 2
4. If step 2 and 3 are inapplicable, print node.
5. Go to step 3
Binary Search Tree Inorder
• Used to get the infix expressions of the binary search tree
• Used by programs that usually have a best case of sorted algorithms
• Human-friendly as it is just basically in ascending order
• Steps:
1. Traverse to the leftmost node and print
2. Go up one parent node and print
3. Traverse to the right subtree (if applicable)
4. Go to step 1
Binary Search Tree Postorder
• Used to get the postfix expressions of the binary search tree
• Used by programs that have a better time complexity with postfixes
• Steps:
1. Traverse to the leftmost node and print
2. Go up one parent node
3. Traverse to the right node and print
4. Go to step 1
• Preorder
• 25, 15, 10, 4, 12, 22, 18, 24, 50, 35, 31, 44, 70, 66, 90
• Inorder
• 4, 10, 12, 15, 18, 22, 24, 25, 31, 35, 44, 50, 66, 70, 90
• Postorder
• 4, 12, 10, 18, 24, 22, 15, 31, 44, 35, 66, 90, 70, 50, 25
Lecture Act 6 (Group Activity): 10 pts
1. Draw a Binary Search Tree and follow the instructions:
• insert() = {50, 20, 80, 0, 40, 35, 90, 100, 45, 85, 60}
• Transpose the elements of the calculated node to the corresponding String:
• 10*2*2 = “DH” • 100-10*2 = “OR”
• 31-1-1-1+7 = “O” • 6*6+3*8 = “G”
• 50/1 = “CH”
• 1*10/5*15*3+10 = “HE”
• 90*10/10 = “T”
• 599%9+80 = “HT”
• 5%1 = “H”
• 5+5*2*4 = “L”
• sqrt(400) = “I”
Lecture Act 6 (Group Activity): 10 pts cont
Based on the current drawn graph, traverse and print the following:
• PreOrder
• InOrder
• PostOrder