Faculty of Mathematical Economics
Data Structures and Algorithms
Instructor: Nguyen Thanh Tuan
DSEB Class of 2021 - 2024
Homework Assignment Week 9
Topic: Tree Traversal Algorithms
Date Created: March 30, 2023
Problem 1: Tree Traversal Algorithms Implementation
a. Implement these following tree traversal algorithms in BinaryTree class.
• Preorder Traversal
• Postorder Traversal
• Breadth - First Tree Traversal
• Inorder Traversal
Note:
• The pseudo-code, figure and examples of these algorithms are all in textbook (Part
8.4 - from page 328). Bear in mind that you should follow these instructions to
standardize your implementation (since these algorithms are basic ones).
• In Breadth - First Tree Traversal, you should use Queue (Array-based) class
you have implemented before.
b. Performing these tasks:
• Create a tree as below:
Data Structures and Algorithms Homework Week 9
• Use postorder traversal algorithm to travel the tree and print out the result.
• Use traversal algorithm to print out: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21.
• Use traversal algorithm to print out: 8, 4, 9, 2, 10, 5, 16, 11, 20, 17, 1, 12, 6, 13, 3,
18, 14, 21, 19, 7, 15.
Problem 2: Tree Traversal Applications
The following problems are based on tree traversal algorithms.
• Write a function based on any tree traversal algorithm that you learned to print
out the total number of nodes in a tree.
• Write a function based on any tree traversal algorithm that you learned to print
out number of nodes that has the value smaller than a given number (for example:
9).
• Write a function based on Breadth - First traversal algorithm to calculate the
sum of all elements in the tree.
• Write a function based on any tree traversal algorithm that you learned to print
out the depth of the tree.
Problem 3: Special Traversal of Binary Tree
Given a binary tree as below, identify all diagonal elements that belong to the same
line as the nodes that intersect lines with a slope of -1, and output them. Name of this
traversal algorithm will be revealed at the tutor class.
2
Data Structures and Algorithms Homework Week 9
Output:
Special Traversal of binary tree:
8 10 14
3 6 7 13
14
Observation: Root and root -> right values will be prioritized over all root -> left
values.
Implement this tree traversal algorithm in BinaryTree class.
Guidelines for submission
• Your submission must be under the .ipynb format.
• Your submission will be graded and it is likely that homework grade will contribute
as a component in your GPA.
• If your submission is later than the due date without special consideration approval,
you will receive a penalty on your mark.