Binary Search Trees

advertisement
Binary Search Trees
Chapter 6
1
Objectives
You will be able to
 Implement and use binary search trees in
C++ programs.
 Determine the time complexity of
searching binary search trees.
2
Searching

We often need to find a specific item in
a collection of items.


Or determine that it is not present.
The simplest strategy is a linear search.


Traverse the collection looking for the
target item.
Time for a linear search is O(n).

Grows in proportion to the number of items in
the collection, n.
3
Binary Search


If an array is ordered, we can make the search
much faster by doing a binary search.
If length of the array is 0,



Check the middle item.
If search target is equal


Return that item.
If the search target is less:


Search target is not present. Report failure.
Do a binary search of the lower half.
If the search target greater

Do a binary search of the upper half.
4
Binary Search


Usually outperforms a linear search
Disadvantage:




Requires a sequential storage
Not appropriate for linked lists (Why?)
A linked structure is desirable if we do
very much inserting and deleting.
It is possible to use a linked structure
which can be searched in a binary-like
manner.
5
Binary Search Tree
49
66
28
13


35
62
80
Everything in left subtree is less than root.
Everything in right subtree is greater than root.

Recursively!
6
Tree

A data structure which consists of



a finite set of elements called nodes or vertices.
a finite set of directed arcs which connect the
nodes.
If the tree is nonempty -

One of the nodes (the root) has no incoming arc.
Every other node can be reached by following a
unique sequence of consecutive arcs starting at
the root.
7
Tree Terminology
Root node
• Children of the parent (3)
Leaf nodes
• Siblings to each other
8
Binary Tree

Each node has at most two children

Examples


Results of multiple coin tosses
Encoding/decoding messages in dots and
dashes such as Morse code
9
Implementation

A binary tree ADT can be implemented
either as a linked structure or as an
array.
10
Array Implementation of Binary Trees
0
O
2
1
T
M
4
3
C

E
6
5
P
U
Store node n in location n of the array.
11
Array Implementation of Binary Trees

Works OK for complete trees, not for sparse trees
12
Linked Implementation of Binary Trees

Uses space more efficiently



for incomplete trees
Provides additional flexibility
Each node has two links



One to the left child of the node
One to the right child of the node
If no child node exists for a node, the link is
set to NULL
13
Structural Recursion
The subset of a binary tree consisting of any node
an all of its descendents is a binary tree.
0
O
2
1
T
M
4
3
C
E
6
5
P
U
Invites the use of recursive algorithms on binary trees.
14
Recursive Algorithm for Binary Tree Traversal


If the binary tree is empty
Do nothing
Else
N: Visit the Node, process data
L: Traverse the left subtree
R: Traverse the right subtree
The "anchor"
The inductive step
15
Binary Tree Traversal Order
Three possibilities for inductive step …



Left subtree, Node, Right subtree
Inorder traversal
Node, Left subtree, Right subtree
the preorder traversal
Left subtree, Right subtree, Node
the postorder traversal
16
Binary Search Tree ADT

Binary Search Tree

A Collection of Nodes

Data




Must have <= and == operations
Left Child
Right Child
For each node x

value in left child ≤ value in x ≤ value in right child
17
BST Basic Operations




Construct an empty BST
Determine if BST is empty
Search BST for given item
Insert a new item in the BST


Delete an item from the BST


Maintain the BST property
Maintain the BST property
Traverse the BST


Visit each node exactly once
The inorder traversal will visit the values in the nodes in
ascending order
18
Example


Create new empty C++ console
application project.
Add to project:


genBST1.h
main.cpp
19
main.cpp
#include <iostream>
#include "genBST1.h"
using namespace std;
int main(void)
{
cout << "This is BST_Demo\n";
cin.get();
return 0;
}
Build and test.
20
genBST1.h



Copy from Downloads area:
http://www.cse.usf.edu/~turnerr/Data_Structures/Downloads/
2011_03_02_Binary_Search_Tree/genBST1.h.txt
This is a subset of Drozdek’s genBST.h
template.



Figure 6.8, page 221 ff.
All textbook examples are available on
the author's web site:
http://www.mathcs.duq.edu/drozdek/DSinCpp/
21
BSTNode
//************************ genBST1.h **************************
//
generic binary search tree
#pragma once;
template<class T>
class BSTNode
{
public:
BSTNode()
{
left = right = 0;
}
BSTNode(const T& el, BSTNode *l = 0, BSTNode *r = 0)
{
key = el; left = l; right = r;
}
T key;
BSTNode *left, *right;
};
22
Class BST
template<class T>
class BST
{
public:
BST() {root = 0;}
~BST() {clear();}
void clear()
{
clear(root);
root = 0;
}
// Overloaded
bool isEmpty() const {return root == 0;}
void insert(const T&);
T* search(const T& el) const
{
return search(root, el);
}
// Overloaded
23
Class BST
protected:
BSTNode<T>* root;
void clear(BSTNode<T>*);
T* search(BSTNode<T>*, const T&) const;
//void preorder(BSTNode<T>*);
//void inorder(BSTNode<T>*);
//void postorder(BSTNode<T>*);
//virtual void visit(BSTNode<T>* p) {
//
cout << p->key << ' ';
//}
};
24
BST<T>::clear()
template<class T>
void BST<T>::clear(BSTNode<T> *p)
{
if (p != 0)
{
clear(p->left);
clear(p->right);
delete p;
}
}
25
BST<T>::insert()
template<class T>
void BST<T>::insert(const T& el)
{
BSTNode<T> *p = root, *prev = 0;
// find a place for inserting new node;
while (p != 0)
{
prev = p;
if (p->key < el)
{
p = p->right;
}
else
{
p = p->left;
}
}
26
BST<T>::insert()
if (root == 0)
// tree is empty;
{
root = new BSTNode<T>(el);
}
else if (prev->key < el)
{
prev->right = new BSTNode<T>(el);
}
else
{
prev->left = new BSTNode<T>(el);
}
}
27
BST<T>::search()
template<class T>
T* BST<T>::search(BSTNode<T>* p, const T& el) const
{
while (p != 0)
{
if (el == p->key)
{
return &p->key;
}
if (el < p->key)
{
p = p->left;
}
else
{
p = p->right;
}
}
return 0;
// el was not found
}
28
Test BST Template
#include <iostream>
#include "genBST1.h"
using namespace std;
int main(void)
{
cout << "This is BST_Demo\n";
BST<int> my_BST;
my_BST.insert(13);
my_BST.insert(10);
my_BST.insert(25);
my_BST.insert(2);
my_BST.insert(12);
my_BST.insert(20);
my_BST.insert(31);
my_BST.insert(29);
29
Test BST Template
cout << "Items in
for (int i = 0; i
{
int* result =
if (result !=
{
cout << i
}
}
cout << endl;
cin.get();
return 0;
the tree: ";
< 100; ++i)
my_BST.search(i);
0)
<< " ";
}
30
Test Running
End of presentation
31
Download