Binary Search Tree
Binary Search Tree
A binary search tree is a binary tree that has the following properties
Given a node with value K
All values on the left subtree of K are smaller than K
All values on the right subtree of K are greater than K
There are no repeated values in the tree (optional)
12
9 16
2 11 13 21
1 3 10
Binary Search Trees
12
9 16
2 11 13 21
1 3 10
search(10)
12
9 16
2 11 13 21
1 3 10
search(10)
12
9 16
2 11 13 21
1 3 10
search(10)
12
9 16
2 11 13 21
1 3 10
search(10)
12
9 16
2 11 13 21
1 3 10
search(10)
12
9 16
2 11 13 21
1 3 10
Implementation of Searching
TREE search(TREE tree, int key)
{
while (tree) {
if (key == tree->data) return tree;
if (key < tree->data)
tree = tree->left_child;
else tree = tree->right_child;
}
return NULL;
}
Binary Search Trees (BSTs)
Where is the
smallest element?
Ans: leftmost element
56
26 200
18 28 190 213
12 24 27
Where is second smallest value present?
15
8 20
2 11 27
6 10 12 22 30
3 7 14
Predecessor and Successor
the successor of x.
Predecessor and Successor
15
8 20
2 11 27
6 10 12 22 30
3 7 14
Insertion in Binary Search Trees
To insert an element in a BST we follow the same principle applied in
the searching.
Compare the value to be inserted with the current key and decide if
the new element should be inserted on the left or on the right
The element is always inserted as a leaf in the tree.
insert (target)
12
9 16
2 11 13 21
1 3 10
insert(14)
12
9 16
2 11 13 21
1 3 10
insert(14)
12
9 16
2 11 13 21
1 3 10
insert(14)
12
9 16
2 11 13 21
1 3 10
insert(14)
12
9 16
2 11 13 21
1 3 10 14
Does the order of inserting elements into a tree
matter?
7
v v
3 9
7 3 2 5 3 2 9 3 2 3 5 7 9
2 5
Counting Frequency
Suppose we want to know the frequency of all the words
occuring in the book, “Tale of two cities”
Assumptions:
book has 135,000+ words
about 10,000 distinct words
What is the best data structure?
1) unordered array
2) unordered linked list
3) ordered array with binary search
4) Binary Search Tree
struct tree
{
char data[20];
int count;
struct tree *left, *right;
};