Today: Trees
Today: Trees
COMPUTER SCIENCE
Today: Trees
Students let us examine ...
BINARY TREES
Trees (cont’d)
A general tree is defined as one or more nodes such that the tree T
is partitioned into disjoint subsets:
A single node, the root r
Sets that are general trees, called subsets or r
The I.B. curriculum want you to focus on binary trees, which are
defined as a set of nodes T in which:
T is empty, or
T is partitioned into three disjoint subsets:
A single node r, the root
Two possibly empty sets that are binary trees, called the
left and right sub-trees of r r
So simply, T is a binary tree if it
has no nodes, or is of the form: TL TR
Trees (cont’d)
A full binary tree is when every node up to a certain level is present:
1 level, 1 node 2 levels, 3 nodes 3 levels, 7 nodes 4 levels, 15 nodes
B E
Equal nodes aren’t
A C G
usually allowed in
ordered
H
binary trees F
If a tree is unordered, then to search, you must traverse the whole tree node by node
(seen later)
However, if a tree is
ordered, you can use
a binary search of the
tree to increase
efficiency, as well this
can be done
recursively, for
example:
TRAVERSING A TREE
Trees (cont’d)
To ‘traverse’ a tree means to visit every node
Traverse algorithms are the same for ordered and
unordered trees
The reasons for traversals could include: printing all
node values, counting nodes, searching the nodes, etc.
There are 3 orders to the traversals:
1. Pre-order
2. In-order
3. Post-order
These traversals can also be accomplished recursively
Trees (cont’d)
In a Pre-order
traversal:
60
1. Visit the
current node 20 70
(starting at the 10 40
root)
2. Traverse the 30 50
left sub-tree 60 20 10 40 30 50 70
3. Traverse the
right sub-tree
The algorithm for this can be seen here:
Trees (cont’d)
In a Post-order
traversal: 60
1. Traverse the 20 70
left sub-tree
10 40
2. Traverse the
right sub-tree 30 50
3. Visit the 10 30 50 40 20 70 60
root node
(of the
sub-tree)
The algorithm for this can be seen here:
Trees (cont’d)
In a In-order
traversal: 60
1. Traverse the 20 70
left
10 40
sub-tree
2. Visit the root 30 50
node 10 20 30 40 50 60 70
(of the
sub-tree)
3. Traverse the right sub-tree
The algorithm for this can be seen here:
Students now we turn our attention to…
2
9
1 4 8 10
3 7
6
Students now we turn our attention to…
10 40 10, 40
30 50 30, 50
There is no easy recursive method for doing this, the best way to
program this is using a queue:
You would get a node from the queue, put it’s left child on the queue,
then put it’s right child on the queue
Trees (cont’d)
Removing a node from a tree can be more difficult, and three scenarios exist:
1. The node has 0 children Set to
2. The node has 1 child 5 null