0% found this document useful (0 votes)
9 views19 pages

CH 10

Uploaded by

Dawit Birhanu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views19 pages

CH 10

Uploaded by

Dawit Birhanu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter 10

BINARY TREES

1. General Binary Trees

2. Binary Search Trees

3. Building a Binary Search Tree

4. Height Balance: AVL Trees

5. Splay Trees: A Self-Adjusting Data Structure

Outline Data Structures and Program Design In C++


Transp. 1, Chapter 10, Binary Trees 243  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Binary Trees

DEFINITION A binary tree is either empty, or it consists of a


node called the root together with two binary trees called
the left subtree and the right subtree of the root.

There is one empty binary tree, one binary tree with one node,
and two with two nodes:

and

These are different from each other. We never draw any part of a
binary tree to look like

The binary trees with three nodes are:

Binary Trees Data Structures and Program Design In C++


Transp. 2, Sect. 10.1, Introduction to Binary Trees 244  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Traversal of Binary Trees

At a given node there are three tasks to do in some order: Visit


the node itself (V); traverse its left subtree (L); traverse its right
subtree (R). There are six ways to arrange these tasks:

VLR LVR LRV VRL RVL R L V.

By standard convention, these are reduced to three by consid-


ering only the ways in which the left subtree is traversed before
the right.

VLR LVR LRV


preorder inorder postorder

These three names are chosen according to the step at which the
given node is visited.

With preorder traversal we first visit a node, then traverse


its left subtree, and then traverse its right subtree.

With inorder traversal we first traverse the left subtree,


then visit the node, and then traverse its right subtree.

With postorder traversal we first traverse the left subtree,


then traverse the right subtree, and finally visit the node.

Traversal of Binary Trees Data Structures and Program Design In C++


Transp. 3, Sect. 10.1, Introduction to Binary Trees 245  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Expression Trees

+ log !

a b x n

a+b log x n!

– or

a × < <

b c a b c d

a – (b × c) (a < b) or (c < d)

Expression: a+b log x n! a − (b × c) (a < b) or (c < d)

Preorder : +a b log x ! n −a ×bc or < a b < c d


Inorder : a+b log x n! a −b×c a < b or c < d
Postorder : a b+ x log n! a bc×− a b < c d < or

Expression Trees Data Structures and Program Design In C++


Transp. 4, Sect. 10.1, Introduction to Binary Trees 246  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
a
×

0.5)/(2 × a)
/

0.5

x := (−b + (b 2 − 4 × a × c)
c
×

a
×

4
2
:=

b
b

x
Expression tree of the quadratic formula Data Structures and Program Design In C++
Transp. 5, Sect. 10.1, Introduction to Binary Trees 247  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Linked Binary Trees

Comparison tree:
Jim

Dot Ron

Amy Guy Kay Tim

Ann Eva Jan Jon Kim Roy Tom

Linked implementation of binary tree:

Jim

Dot Ron

Amy Guy Kay Tim

Ann Eva Jan Jon Kim Roy Tom

Linked Binary Trees Data Structures and Program Design In C++


Transp. 6, Sect. 10.1, Introduction to Binary Trees 248  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Linked Binary Tree Specifications

Binary tree class:


template < class Entry >
class Binary tree {
public:
// Add methods here.
protected:
// Add auxiliary function prototypes here.
Binary node< Entry > *root;
};

Binary node class:

template < class Entry >


struct Binary node {

// data members:
Entry data;
Binary node< Entry > *left;
Binary node< Entry > *right;
// constructors:
Binary node( );
Binary node(const Entry &x);

};

Linked Binary Tree Specifications Data Structures and Program Design In C++
Transp. 7, Sect. 10.1, Introduction to Binary Trees 249  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Constructor:

template < class Entry >


Binary tree< Entry > :: Binary tree( )
/* Post: An empty binary tree has been created. */
{
root = NULL;
}

Empty:

template < class Entry >


bool Binary tree< Entry > :: empty( ) const
/* Post: A result of true is returned if the binary tree is empty. Otherwise, false is
returned. */
{
return root == NULL;
}

Binary tree methods Data Structures and Program Design In C++


Transp. 8, Sect. 10.1, Introduction to Binary Trees 250  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Inorder traversal:

template < class Entry >


void Binary tree< Entry > :: inorder(void (*visit)(Entry &))
/* Post: The tree has been been traversed in inorder sequence.
Uses: The function recursive inorder */
{
recursive inorder(root, visit);
}

Most Binary tree methods described by recursive processes can


be implemented by calling an auxiliary recursive function that
applies to subtrees.

template < class Entry >


void Binary tree< Entry > ::
recursive inorder(Binary node< Entry > *sub root,
void (*visit)(Entry &))
/* Pre: sub root is either NULL or points to a subtree of the Binary tree.
Post: The subtree has been been traversed in inorder sequence.
Uses: The function recursive inorder recursively */
{
if (sub root != NULL) {
recursive inorder(sub root->left, visit);
(*visit)(sub root->data);
recursive inorder(sub root->right, visit);
}
}

Binary tree methods Data Structures and Program Design In C++


Transp. 9, Sect. 10.1, Introduction to Binary Trees 251  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Binary Tree Class Specification

template < class Entry >


class Binary tree {
public:
Binary tree( );
bool empty( ) const;
void preorder(void (*visit)(Entry &));
void inorder(void (*visit)(Entry &));
void postorder(void (*visit)(Entry &));

int size( ) const;


void clear( );
int height( ) const;
void insert(const Entry &);

Binary tree (const Binary tree< Entry > &original);


Binary tree & operator = (const Binary tree< Entry > &original);
∼ Binary tree( );
protected:
// Add auxiliary function prototypes here.
Binary node< Entry > *root;
};

Binary Tree Class Specification Data Structures and Program Design In C++
Transp. 10, Sect. 10.1, Introduction to Binary Trees 252  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Binary Search Trees

Can we find an implementation for ordered lists in which


we can search quickly (as with binary search on a contigu-
ous list) and in which we can make insertions and deletions
quickly (as with a linked list)?

DEFINITION A binary search tree is a binary tree that is


either empty or in which the data entry of every node has a
key and satisfies the conditions:
1. The key of the left child of a node (if it exists) is less than
the key of its parent node.
2. The key of the right child of a node (if it exists) is greater
than the key of its parent node.
3. The left and right subtrees of the root are again binary
search trees.

We always require:
No two entries in a binary search tree may have equal keys.

We can regard binary search trees as a new ADT.


We may regard binary search trees as a specialization of bi-
nary trees.
We may study binary search trees as a new implementation
of the ADT ordered list.

Binary Search Trees Data Structures and Program Design In C++


Transp. 11, Sect. 10.2, Binary Search Trees 253  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
The Binary Search Tree Class

The binary search tree class will be derived from the binary
tree class; hence all binary tree methods are inherited.

template < class Record >


class Search tree: public Binary tree< Record > {
public:
Error code insert(const Record &new data);
Error code remove(const Record &old data);
Error code tree search(Record &target) const;
private: // Add auxiliary function prototypes here.
};

The inherited methods include the constructors, the destruc-


tor, clear, empty, size, height, and the traversals preorder, inorder,
and postorder.

A binary search tree also admits specialized methods called


insert, remove, and tree search.

The class Record has the behavior outlined in Chapter 7: Each


Record is associated with a Key. The keys can be compared
with the usual comparison operators. By casting records to
their corresponding keys, the comparison operators apply to
records as well as to keys.

The Binary Search Tree Class Data Structures and Program Design In C++
Transp. 12, Sect. 10.2, Binary Search Trees 254  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Tree Search

Error code Search tree< Record > ::


tree search(Record &target) const;
Post: If there is an entry in the tree whose key matches that
in target, the parameter target is replaced by the corre-
sponding record from the tree and a code of success is
returned. Otherwise a code of not present is returned.

This method will often be called with a parameter target that


contains only a key value. The method will fill target with the
complete data belonging to any corresponding Record in the
tree.
To search for the target, we first compare it with the entry
at the root of the tree. If their keys match, then we are fin-
ished. Otherwise, we go to the left subtree or right subtree as
appropriate and repeat the search in that subtree.
We program this process by calling an auxiliary recursive
function.
The process terminates when it either finds the target or hits
an empty subtree.
The auxiliary search function returns a pointer to the node
that contains the target back to the calling program. Since
it is private in the class, this pointer manipulation will not
compromise tree encapsulation.

Binary node< Record > *Search tree< Record > :: search for node(
Binary node< Record >* sub root, const Record &target) const;
Pre: sub root is NULL or points to a subtree of a Search tree
Post: If the key of target is not in the subtree, a result of NULL
is returned. Otherwise, a pointer to the subtree node
containing the target is returned.

Tree Search Data Structures and Program Design In C++


Transp. 13, Sect. 10.2, Binary Search Trees 255  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Recursive auxiliary function:

template < class Record >


Binary node< Record > *Search tree< Record > :: search for node(
Binary node< Record >* sub root, const Record &target) const
{
if (sub root == NULL || sub root->data == target)
return sub root;
else if (sub root->data < target)
return search for node(sub root->right, target);
else return search for node(sub root->left, target);
}

Nonrecursive version:

template < class Record >


Binary node< Record > *Search tree< Record > :: search for node(
Binary node< Record > *sub root, const Record &target) const
{
while (sub root != NULL && sub root->data != target)
if (sub root->data < target) sub root = sub root->right;
else sub root = sub root->left;
return sub root;
}

Auxiliary functions, tree search Data Structures and Program Design In C++
Transp. 14, Sect. 10.2, Binary Search Trees 256  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Public method for tree search:

template < class Record >


Error code Search tree< Record > ::
tree search(Record &target) const
/* Post: If there is an entry in the tree whose key matches that in target, the
parameter target is replaced by the corresponding record from the tree
and a code of success is returned. Otherwise a code of not present
is returned.
Uses: function search for node */
{
Error code result = success;
Binary node< Record > *found = search for node(root, target);
if (found == NULL)
result = not present;
else
target = found->data;
return result;
}

Tree search functions Data Structures and Program Design In C++


Transp. 15, Sect. 10.2, Binary Search Trees 257  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Binary Search Trees with the Same Keys

d e

b f b f

a c e g a d g

(a) c

(b)

a a a

g b
b

e g
c
b f f
d
d c

e
c e

(c) d f

(d)
g

(e)

Binary Search Trees with the Same Keys Data Structures and Program Design In C++
Transp. 16, Sect. 10.2, Binary Search Trees 258  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Analysis of Tree Search

Draw the comparison tree for a binary search (on an ordered


list). Binary search on the list does exactly the same compar-
isons as tree search will do if it is applied to the comparison
tree. By Section 7.4, binary search performs O(log n) com-
parisons for a list of length n . This performance is excellent
in comparison to other methods, since log n grows very slowly
as n increases.
The same keys may be built into binary search trees of many
different shapes.
If a binary search tree is nearly completely balanced (“bushy”),
then tree search on a tree with n vertices will also do O(log n)
comparisons of keys.
If the tree degenerates into a long chain, then tree search be-
comes the same as sequential search, doing 2(n) comparsions
on n vertices. This is the worst case for tree search.
The number of vertices between the root and the target, in-
clusive, is the number of comparisons that must be done to
find the target. The bushier the tree, the smaller the number
of comparisons that will usually need to be done.
It is often not possible to predict (in advance of building it)
what shape of binary search tree will occur.
In practice, if the keys are built into a binary search tree
in random order, then it is extremely unlikely that a binary
search tree degenerates badly; tree search usually performs
almost as well as binary search.

Analysis of Tree Search Data Structures and Program Design In C++


Transp. 17, Sect. 10.2, Binary Search Trees 259  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Insertion into a Binary Search Tree

Error code Search tree< Record > ::


insert(const Record &new data);
Post: If a Record with a key matching that of new data al-
ready belongs to the Search tree a code of duplicate error
is returned. Otherwise, the Record new data is inserted
into the tree in such a way that the properties of a bi-
nary search tree are preserved, and a code of success
is returned.

e e e

b b

d
(a) Insert e (b) Insert b (c) Insert d

e e

b f b f

d a d
(d) Insert f (e) Insert a

e e

b f b f

a d g a d g

c
(f) Insert g (g) Insert c

Insertion into a Binary Search Tree Data Structures and Program Design In C++
Transp. 18, Sect. 10.2, Binary Search Trees 260  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458
Method for Insertion

template < class Record >


Error code Search tree< Record > :: insert(const Record &new data)
{
return search and insert(root, new data);
}

template < class Record >


Error code Search tree< Record > :: search and insert(
Binary node< Record > * &sub root, const Record &new data)
{
if (sub root == NULL) {
sub root = new Binary node< Record >(new data);
return success;
}
else if (new data < sub root->data)
return search and insert(sub root->left, new data);
else if (new data > sub root->data)
return search and insert(sub root->right, new data);
else return duplicate error;
}

The method insert can usually insert a new node into a ran-
dom binary search tree with n nodes in O(log n) steps. It
is possible, but extremely unlikely, that a random tree may
degenerate so that insertions require as many as n steps.
If the keys are inserted in sorted order into an empty tree,
however, this degenerate case will occur.

Method for Insertion Data Structures and Program Design In C++


Transp. 19, Sect. 10.2, Binary Search Trees 261  1999 Prentice-Hall, Inc., Upper Saddle River, N.J. 07458

You might also like