Professional Documents
Culture Documents
Binary Search Trees
Binary Search Trees
Definition
Operations
A. Kostanyan
1
Definition
The Binary Search Tree (or, simply Search Tree) is a
binary tree representation of a set of keys such that the
key at every node x is greater than or equal to the keys of
the sub-tree rooted at x.left, and less than or equal to the
keys at the sub-tree rooted at x.right.
The search tree T supports the following operations:
find(T, k); // returns true, iff k belongs to T
insert(T, k); //inserts k into T
remove(T, k); //removes k from T
Note: The inorder traversal of a search tree results in a sorted
sequence of keys.
A. Kostanyan
2
Example
50
20 70
10 40 60 80
15 30 65 75
10 40 60 80 10 40 60 80
15 30 65 75 15 30 65 75
false
A. Kostanyan
4
Insertion
insert(T, k);
To insert the key k into the search tree T, find the parent node y for k
(if any) by moving top-down in T, create a node x with k, and make x
either left or right child of y, depending on whether k<y.key.
Example:
50 50
insert(35)
70 70
20 20
10 40 60 80 10 40 60 80
y
15 30 65 75 15 30 65 75
x
35
Note: Newly inserted node is always added
as a leaf into a binary tree!
A. Kostanyan
5
Removal
remove(T, k);
To remove one of the occurrences of key k from the search tree T, find a
node x containing k (if any), then consider the following 3 cases:
Case 1. x does not have a left child.
- If there is a parent node z for x, then the link leading from z to x
redirect to x.rlink. Else, make T.root equal to x.rlink.
- If there is a right child y for x, then make y.parent equal to x.parent.
- Delete x.
Example:
50 50
z remove(10) z
70 70
20 20
x y
10 40 60 80 15 40 60 80
y 65 75 30 65 75
15 30
A. Kostanyan
6
Removal – (2)
Case 2. x has a left child y but does not have a right child.
- If there is a parent node z for x, then the link leading from z to x
redirect to x.llink. Else, make T.root equal to x.llink.
- Make y.parent equal to x.parent.
- Delete x.
Example:
50 50
z remove(40) z
70 70
20 x 20 y
10 40 60 80 10 30 60 80
15 30 y 65 75 15 65 75
A. Kostanyan
7
Removal – (3)
Case 3. x has two children.
- Find the leftmost node y in the subtree rooted at x.rlink.
- Make x.key equal to y.key and remove the node y (definitely
not having a left child) from T according to case 1.
Example: x
x
50 60
remove(50)
70 70
20 20
y
10 40 60 80 10 40 65 80
15 30 65 75 15 30 75
A. Kostanyan
8
Additional Operations
min (T);
Returns the minimal key that belongs to a non-empty search tree T
max (T);
Returns the maximal key that belongs to a non-empty search tree T
A. Kostanyan
9
Complexity
If the height of the search tree T is h, then all the
operations considered above obviously have complexity
O(h).
A. Kostanyan
10