BinarySearchTrees
BinarySearchTrees
Binary Trees
Binary tree is A
a root
left subtree (maybe empty)
right subtree (maybe B C
empty)
D E F
Properties
max # of leaves:
max # of nodes:
G H
average depth for N nodes:
Data I J
Representation: left right
pointer pointer
Binary Search CSE 326 Autumn 2001
Trees 2
Binary Tree
Representation
A A
left right
child child
B C
B C
left right left right
child child child child D E F
D E F
left right left right left right
child child child child child child
…
Stores values associated with user-
specified keys
values may be any (homogeneous)
type
keys may be any (homogeneous)
comparable type
Binary Search CSE 326 Autumn 2001
Trees 4
Dictionary ADT:
Used Everywhere
Arrays
Sets
Dictionaries
Router tables
Page tables
Symbol tables
C++ structures
…
Fast searching
runtime:
Fast deletion
runtime:
1 4 6
2 9 20
What does this
guarantee with a
7 17 30 BST?
In order listing:
25791015172030
Binary Search CSE 326 Autumn 2001
Trees 12
Recursive Find
10
Node *
find(Comparable key, Node * t)
5 15
{
if (t == NULL) return t;
2 9 20
else if (key < t->key)
return find(key, t->left);
7 17 30
else if (key > t->key)
return find(key, t->right);
Runtime: else
Best-worse case? return t;
Worst-worse case? }
f(depth)?
Binary Search CSE 326 Autumn 2001
Trees 13
Iterative Find
10
Node *
find(Comparable key, Node * t)
5 15 {
while (t != NULL && t->key != key)
{
2 9 20
if (key < t->key)
t = t->left;
7 17 30 else
t = t->right;
}
return t;
}
} else {
// duplicate
// handling is app-dependent
}
Binary Search CSE 326 Autumn 2001
Trees 15
BuildTree for BSTs
Suppose the data 1, 2, 3, 4, 5, 6, 7, 8, 9 is
inserted into an initially empty BST:
in order
in reverse order
1 + 2 + 3 + … + n = O(n2)
5 15
Find maximum
2 9 20
7 17 30
5 15
2 9 20
7 17 30
Delete(5) 5 15
Find(9) 2 9 20
Find(16)
7 17 30
Insert(5)
Find(17)
Binary Search CSE 326 Autumn 2001
Trees 23
Deletion - Leaf Case
Delete(17) 10
5 15
2 9 20
7 17 30
5 15
2 9 20
7 30
2 9 30
Delete(5)
7
Realities
For large data sets, disk accesses dominate runtime
Some deep and some shallow BSTs exist for any data
What matters?
Problems occur when one branch is much longer than
another
i.e. when tree is out of balance