Classroom practice: Binary trees.
Gábor Horváth / Zsolt Kohári · 2020.12.11.
Binary trees and related recursive algorithms.
Preparation for the practice:
- The lecture notes on recursion should be reviewed.
- The lecture notes on trees should be reviewed.
Building trees
Let us insert the following numbers into a binary search tree, in the given order, without balancing the tree: 5, 8, 3, 6, 7, 2, 9, 1. Draw the resulting binary tree!
Properties of trees
o
/ \
o o
/ / \
o o o
/ \
o o
What is the height of this tree? How many leaves does it have?
Traversing trees
3
/ \
4 9
/ / \
2 6 5
/ \ \
1 7 0
Is the binary tree above a binary search tree? In which order are the elements of the tree visited in case of a) inorder b) postorder c) preorder traversal?
Define the appropriate type for the following binary trees!
- Binary tree to store words and the number of their occurrences.
- Binary tree to store names and phone numbers (the name can be arbitrary long). (Mind that it is not enough to use integers for storing phone "numbers")
- We would like to decode Morse code as fast as possible with a binary tree. The two possible characters in Morse code are "." and "-". Depending on the next Morse character we can either go to the left (".") or to the right ("-") in this tree. When the character sequence ends, the corresponding latin letter can be found in the current node of the tree.
Let us use the type defined in the previous exercise to store contacts consisting of names and phone numbers in a binary search tree, ordered by the names. Create a C function that receives a pointer to the root of the tree and lists the phone numbers of all people called "Smith", in lexicographical ordering! (It is logical to store names 'family name first', as e.g. "Miller, Arthur".)