Binary Trees

advertisement
Binary trees
BINARY TREES IN GENERAL















A tree is a structure in which data can be held
Each item of data points to two others
A rule is needed for determining the route taken from any data item
The data items are held in nodes and the possible routes are paths
Each node has two possible paths and the nodes are arranged in layers
The first node is called the root
Students in the class are: David, Barbara, Chris, Ann, Ewan
We start on layer 1 with David as the root
Items of data are inserted into trees at nodes and this first is called the root node
All subsequent layers need a rule, as this is a text list alphabetical will do
IF the next name is higher in alphabetical order go right, if its lower go left
The next name is Barbara so we go left
The next name is Chris.
This is lower in alphabetical order than David so we need to go left to Barbara
Chris is higher than Barbara so we go right
What do we get if we now add ANN and EWAN?






We add ANN LEFT of DAVID, LEFT of BARBARA
We add EWAN RIGHT of DAVID
Therefore we should have a tree structure which looks like:
It is possible to have trees that have more than two routes out of a node
But they are not as useful in computer science
Trees that are limited to a maximum of two routes out of a node are called binary trees
•
Reading Trees
•
•
•
•
•
•
•
•
There are a number of ways of reading a tree, one of which follows:
We need rules and this particular rule set is as follows:
At each node:
If there is a left branch that has not been traversed (followed) then follow it and repeat
Read node if not already read
If there is a right branch, traverse it and repeat
Go back up one layer
Application of these rules to our original tree gives:
TREES STORING
• Trees can be stored in arrays using two pointers for each data item
• The first pointer points to the left node in the next later
• The second pointer points to the right node in the next layer
• If there is no link then the null value is inserted
• Deleting data from a tree is more difficult than it would at first seem
• Consider moving Barbara from the tree
• How can we find anyone who is below Barbara’s layer?
• Not only was Barbara a data item, but it was also an important part of the tree
structure
Deleting data
•
•
•
•
The node to be deleted has no children.
In this case the node may simply be deleted from the tree.
The node has one child.
The child node is appended to its grandparent. (The parent of
the node to be deleted.)
• The node to be deleted has two children
• The order of the binary tree must be kept intact. The algorithm
must determine which node to use in place of the node to be
deleted.
Use the in order successor of the node to be deleted:
• Else if no right sub tree exists
replace the node to be deleted with the it's left child.
The root node
Download