1 Binary Search Trees Chapter 6. 2 Objectives You will be able to Implement and use binary search...
-
Upload
griffin-hudson -
Category
Documents
-
view
214 -
download
0
Transcript of 1 Binary Search Trees Chapter 6. 2 Objectives You will be able to Implement and use binary search...
1
Binary Search Trees
Chapter 6
2
Objectives
You will be able to Implement and use binary search
trees in C++ programs. Determine the time complexity of
searching binary search trees.
3
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.
4
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, Search target is not present. Report failure.
Check the middle item. If search target is equal
Return that item. If the search target is less:
Do a binary search of the lower half. If the search target greater
Do a binary search of the upper half.
5
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.
6
Binary Search Tree
Everything in left subtree is less than root. Everything in right subtree is greater than root.
Recursively!
49
80
62
35
13
66
28
7
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.
8
Tree Terminology
Root nodeRoot node
Leaf nodesLeaf nodes
• Children of the parent (3)
• Siblings to each other
• Children of the parent (3)
• Siblings to each other
9
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
Implementation
A binary tree ADT can be implemented either as a linked structure or as an array.
10
11
Array Implementation of Binary Trees
Store node n in location n of the array.
O
UPEC
TM
0
21
6543
12
Array Implementation of Binary Trees
Works OK for complete trees, not for sparse trees
13
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
14
Structural Recursion
O
UPEC
TM
0
21
6543
The subset of a binary tree consisting of any node an all of its descendents is a binary tree.
Invites the use of recursive algorithms on binary trees.
15
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 "anchor"
The inductive stepThe inductive step
16
Binary Tree Traversal Order
Three possibilities for inductive step …
Left subtree, Node, Right subtreeInorder traversal
Node, Left subtree, Right subtreethe preorder traversal
Left subtree, Right subtree, Nodethe postorder traversal
17
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
Binary Search Tree ADT
18
Construct an empty BST Determine if BST is empty Search BST for given item Insert a new item in the BST
Maintain the BST property Delete an item from the BST
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
BST Basic Operations
19
Example
Create new empty C++ console application project.
Add to project: genBST1.h main.cpp
20
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.
21
genBST1.h
Copy from Downloads area: http://www.cse.usf.edu/~turnerr/Data_Structures/Down
loads/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/
22
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;
};
23
Class BST
template<class T>
class BST
{
public:
BST() {root = 0;}
~BST() {clear();}
void clear() // Overloaded
{
clear(root);
root = 0;
}
bool isEmpty() const {return root == 0;}
void insert(const T&);
T* search(const T& el) const // Overloaded
{
return search(root, el);
}
24
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 << ' ';
//}
};
25
BST<T>::clear()
template<class T>
void BST<T>::clear(BSTNode<T> *p)
{
if (p != 0)
{
clear(p->left);
clear(p->right);
delete p;
}
}
26
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;
}
}
27
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);
}
}
28
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
}
29
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);
30
Test BST Template
cout << "Items in the tree: ";
for (int i = 0; i < 100; ++i)
{
int* result = my_BST.search(i);
if (result != 0)
{
cout << i << " ";
}
}
cout << endl;
cin.get();
return 0;
}
31
Test Running
End of presentation