Binary Trees Notes
Binary Trees Notes
1. Binary Tree
• A binary tree is another frequently used ADT.
• It is a hierarchical data structure in which each parent node can have a maximum of two child
nodes.
• There are many uses for binary trees; for example, they are used in
o syntax analysis
o compression algorithms
o 3D video games
• The binary tree for the data stored is sorted in ascending order.
• Each item is stored as a node.
• Each node can have up to two branches.
• If the value to be added is less than the current node branch left.
• If the value to be added is greater than or equal to the current node branch right.
ACTIVITY 19J
Draw the binary tree for the expression (x – y) / ( x * y + z)
• The data structure for an ordered binary tree can be created in pseudocode as follows:
ACTIVITY 19K
Create the data structure in pseudocode for a binary tree to store a list of names. Your list must be
able to store at least 50 names.
• Here is the identifier table for the binary tree search algorithm shown above.
Identifier Description
myTree Tree to be searched
node ADT for tree
rootPointer Pointer to the start of the tree
leftPointer Pointer to the left branch
rightPointer Pointer to the right branch
nullPointer Null pointer set to −1
itemPointer Pointer to current item
itemSearch Item being searched for
• The trace table below shows the algorithm being used to search for 42 in myTree.
ACTIVITY 19L
Use the algorithm to search for 55 and 75 in myTree. Show the results of each search in a trace table.
• The algorithm to insert an item at a new node in the binary tree myTree could be written as a
procedure in pseudocode as shown below:
Identifier Description
myTree Tree to be searched
node ADT for tree
rootPointer Pointer to the start of the tree
leftPointer Pointer to the left branch
rightPointer Pointer to the right branch
nullPointer Null pointer set to −1
itemPointer Pointer to current item
itemAdd Item to add to tree
nextFreePointer Pointer to next free node
itemAddPointer Pointer to position in tree to store item to be added
oldPointer Pointer to leaf node that is going to point to item added
leftBranch Flag to identify whether to go down the left branch or the right branch
• The trace table below shows the algorithm being used to add 18 to myTree.
ACTIVITY 19M
Use the algorithm to add 25 to myTree. Show this in a trace table and show myTree once 25 has been
added.