Set07 Binary Trees BST Ed 2perpage
Set07 Binary Trees BST Ed 2perpage
Learning Goals:
1
Domain: A set of nodes containing: (a) some application data (e.g.,
one or more of: name, student #, GPA, …), and (b) two (possibly
NULL) pointers to other nodes.
Structure: There is a unique root node (that has no parent node)
having zero, one, or two child nodes; every other node has exactly
one parent node and either zero, one, or two children.
Operations:
insertLeft - insert new node as left child of given node
insertRight - insert new node as right child of given node
find - find node containing given item (i.e., a “search key”)
findParent - find parent of given node
deleteItem - remove node containing given item
print - print data in the tree
etc.
Some Terminology:
The path from node N1 to node Nk is a sequence of nodes
N1, N2, …, Nk where Ni is the parent of Ni+1. The length of the path
is the number of edges in the path. (Warning: Some texts use the
number of nodes rather than the number of edges).
The depth or level of a node N is the length of the path from the root
to N. The level of the root is 0.
The height of a node N is the length of the longest path from N to a
leaf node (a node with no child). The height of a leaf node is 0.
The height of a tree is the height of its root node
node. The height of the
empty tree is –1. The root appears at level 0.
The number of nodes in a tree of height h is at least h+1 and no more
than 2h+1-1.
2
E
H C
B D J I
F G
A
Height of tree:
Depth of node containing B:
Height
i h off node
d containing
i i B:
# of nodes in this tree:
# of leaves (i.e., external nodes):
# of non-leaf (i.e., internal) nodes:
CPSC 221 Binary Trees Page 5
Complete Binary Tree: A full binary tree where all leaves have the
same depth. Examples:
Nearly
N l Complete
C l t Binary
Bi Tree:
T All leaves
l on the
th last
l t level
l l are
together on the far left side, and all other levels are completely filled.
Examples:
3
At this stage in the course, we assume that binary trees are arbitrarily
ordered (i.e., there is no order to their keys).
The number of distinct binary trees with n nodes is given by the
Catalan number having the formula:
f(n) = (2n)! / ((n+1)!n!)
How many distinct binary trees are there when n=3?
Draw them.
4
Bnode * makeNode(const Item_type& item,
Bnode * leftChild = NULL, Bnode * rightChild = NULL)
// PRE: item is valid, leftChild points to a node or is
// NULL, rightChild points to a node or is NULL
// POST: a new node is created and its address is
// returned
{
Bnode * temp;
temp = new Bnode;
temp->item = item;
temp->left = leftChild;
i
temp->right = rightChild;
return temp;
}
5
Consider the insertLeft function. This function is used to insert an
item in a node to the left of a current node (or to create a new binary
tree). We assume that current does not already have a left child; so
we are inserting into an “empty” spot in the tree:
void insertLeft( BNode*& current,
const Item_type& item )
// PRE: current points to a node in a binary tree or
// is NULL
// POST: if current is not null, the left child of
// current is a new node containing item; else,
// current points to a root node containing item
{
if (current) // same as: “if
if (current !=
! NULL)
NULL)”
current->left = makeNode(item);
else
current = makeNode(item);
}
CPSC 221 Binary Trees Page 11
6
We will now consider the deleteNode function. The task of
removing a node from a binary tree is quite complicated; therefore,
we will break the task into parts (a full version is on WebCT).
bool deleteNode( BNode*& root, const Item_type& item )
// PRE: root points to the root of a binary tree or is
// NULL
// POST: if item is in tree, first instance of node
// containing item has been deleted and true is
// returned; else, false is returned (only)
{
Bnode *temp, *parent;
temp
p = find(root, item);
if (!temp) // same as: if (temp == NULL)
return false;
// temp now points to the node containing item
parent = findParent(root, temp);
CPSC 221 Binary Trees Page 13
Now that we have a reference to the pointer that points to the node to
be deleted, we proceed according to one of 4 cases:
Case 1: node to be deleted is a leaf
if (isLeaf(temp))
{
if (parent) // “if (parent != NULL)”
if (parent->left == temp)
parent->left = NULL;
else
parent->right = NULL;
else
root = NULL;;
7
Case 2: node to be deleted has both a left and right child
This is the tricky case. There is no obvious way to remove a node
having two children and re-connect the tree. Instead, we will choose
not to delete the node but rather copy data from a leaf node (which is
easyy to remove)) into the current node. We will arbitrarilyy choose to
copy data from the leftmost leaf of the node to be deleted (if the
nodes’ keys are in arbitrary order).
Case 4: node to be deleted has only a right child (see WebCT Vista)
(same idea)
CPSC 221 Binary Trees Page 16
8
Tree Traversals
There are three common types of binary tree traversals:
Preorder (prefix): “process” the current node, then recursively visit
its left subtree, then recursively visit its right subtree
5
8 3
2 4 0 7
9 1
6
Inorder (infix): visit the left subtree, then process the current node,
then visit the right subtree
5
8 3
2 4 0 7
9 1
6
Data printed using inorder traversal:
9
Postorder (postfix): visit the left subtree, then visit the right subtree,
then process the current node
5
8 3
2 4 0 7
9 1
6
Data printed using postorder traversal:
10
An Application: Binary Expression Trees
Arithmetic expressions can be represented using binary trees. We
will build a binary tree representing the expression:
(3+2)*5–1
We start by identifying the operator with the highest precedence and
build a binary tree having the operator at the root, the left operand as
the left subtree and the right operand as the right subtree. We
continue in this fashion until all operators have been represented:
(3 + 2 )
(3 + 2) * 5
(3 + 2) * 5 – 1
11
Binary Search Trees (Review, and C++ Implementation):
A binary search tree (BST) is a binary tree such that for every node
v in the tree: (a) all of the keys (elements) in v’s left subtree are ≤
v’s key, and (b) all of the keys in v’s right subtree are ≥ v’s key.
6 6
3 7 5 7
2 5 9 2 3 9
2 5 9
12
In the following implementations of the Search function, we assume
that the nodes of the binary search tree are represented as follows:
template<typename Key, typename Value>
struct BNode
{
Key key;
Value value;
Bnode * left;
Bnode * right;
};
13
Alternatively, if we want to return a pointer to the node containing
the found search key (or NULL if no such node exists), we can use
the following code (and this time, we’ll use an iterative version):
template<typename Key, typename Value>
BNode<Key, Value>* search( BNode<Key, Value>* root,
const Key& key
k )
{
while (root && root->key != key)
if (key > root->key)
root = root->right; // right subtree
else
root = root->left; // left subtree
return root;
}
14
Drawing exercise: Insert the following keys (we won’t worry about
the corresponding values) into an empty binary search tree in the order
given. Note that in both cases, the data is the same but the order in
which we do the insertion is different.
Case 1: 7, 4, 3, 6, 9, 8
Case 2: 3, 4, 6, 7, 8, 9
15
Removing an Item from a BST
Algorithm:
Search for the item to find the node containing the item.
If the item was not found, we’re done.
If the node is a leaf, delete the node.
If node’s
d ’ lleft
f subtree
b iis empty, replace
l node
d with
i h right
i h child
hild
else if node’s right subtree is empty, replace node with left child
else replace node with its logical predecessor (rightmost node of
its left sub-tree)
2 5 9
2 5 9
2 5 9
Note that by replacing the node with its logical predecessor (or logical
successor), we maintain the ordering property of the binary search tree.
CPSC 221 Binary Trees Page 32
16
Finding the Smallest Key in a BST, Recursively
Assuming the tree is reasonably balanced, we can access the smallest
(or largest) item in O(_____) time because the smallest and largest
items in a BST are stored in the extreme left and extreme right nodes
of the tree.
}
CPSC 221 Binary Trees Page 33
This is a Θ(____) operation (worst case, average case, and best case).
17