Lecture 9 Binary Search Trees
Lecture 9 Binary Search Trees
2
Binary Search Trees
3
Binary Search Trees
► All items (keys) in the left subtree are less than the
root’s key
4
Binary Search Trees
5
Binary Search Trees vs Binary Trees
6 6
2 8 2 8
1 4 1 4
3 3 7
6
Examples - Non Binary Search Trees
a) 22 > 17
Here we see more examples of b) 11 < 17
binary trees that are not binary
search trees … why? c) 11 > 6
d) 22 > 17
7
Representation of BSTs
8
Binary Search Trees
9
Search Tree Property:Duplicate Keys
10
Binary Search Trees
▪ Operations
► Insertion
► Search
► Traversal
► Deletion
11
Inserting a value into a BST
12
Inserting Item 5 to the Tree
t
6 Tree root node
t
2 8 NULL NULL
t
1 NULL NULL 4 NUL
L
14
Tree Search uses Sub-trees
15
Deleting from a BST
16
remove in a binary search tree
25 40
15
5 20 45 25
15 40
18
removeElement(45)
-------------> 5 20
18
17
remove in a binary search tree
5 20 45
removeElement(20) 25
18
>
15 40
5 18 45
18
remove in a binary search tree
15 40
45 25
5 20
18 40
18
removeElement(15) 45
5 20
>
18
<--- Now remove
this 19
Deleting a node with two children
6 6
2 8 3 8
1 5 1 5
3 3
4 Deletion of node 2 4
20
Minimum Function
22
Successor Function
23
Examples - Successor Function
24
Predecessor Function
25
Examples - Predecessor Function
26
Data Structures: A Pseudocode
Approach with C, Second 27
Edition
Data Structures: A Pseudocode
Approach with C, Second 28
Edition