CS 477/677
Binary Search Trees
Instructor: George Bebis
(Appendix B5.2, Chapter 12)
Node representation:
Key field
Satellite data
Left: pointer to left child
Right: pointer to right child
p: pointer to parent (p [root [T]] =
NIL)
parent
key data
Left child
Right child
5
3
2
7
5
Worst Case
(n)
Preorder: 5 3 2 5 7 9
7
5
Postorder: 2 5 3 9 7 5
6
E.g.:
5
3
2
Output: 2 3 5 5 7 9
7
5
Running time:
(n), where n is the size of the tree rooted at x
7
3
2
7
4
Idea
Example: TREE-SEARCH
15
6
3
2
18
7 17
20
13
9
Alg: TREE-MINIMUM(x)
1. while left [x] NIL
2.
do x left [x]
3. return x
15
6
3
2
18
7 17
20
13
9
Minimum = 2
Alg: TREE-MAXIMUM(x)
1. while right [x] NIL
2.
do x right [x]
3. return x
15
6
3
2
18
7 17
20
13
9
Maximum = 20
12
Successor
Def: successor (x ) = y, such that key [y] is the
smallest key > key [x]
15
E.g.: successor 17
(15) =
15 =
successor (13)
6
18
13 =
successor (9)
3
7 17 y
Case 1: right (x) is non empty
13
9
13
20
15
y
7 17
13
18
20
Predecessor
Def: predecessor (x ) = y, such that key [y] is
the
biggest key < key [x]
15
E.g.: predecessor 13
(15) =
y
7 =
predecessor (9)
x
6
18
6 =
predecessor (7)
3
7 17
20
Case 1: left (x) is non empty
13
9
15
Insertion
Goal:
Insert value v into a binary search tree
Idea:
If key [x] < v move to the right child of x,
Insert value 13
12
5
2
18
9 15
13
19
17
Example: TREE-INSERT
Insert 13:
x=root[T], y=NIL
12
5
2
1
12
18
9 15
5
19
1
9 15
3
2
1
12
y
18
9 15
3
19
17
12
5
18
17
5
2
19
17
18
9 15
13
19
17
x = NIL
y = 15
17
Alg: TREE-INSERT(T, z)
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
y NIL
x root [T]
while x NIL
do y x
if key [z] < key [x]
then x left [x]
else x right [x]
p[z] y
if y = NIL
then root [T] z
else if key [z] < key [y]
then left [y] z
else right [y] z
12
5
2
1
18
9 15
13
19
17
Deletion
Goal:
Delete a given node z from a binary search tree
Idea:
Case 1: z has no children
Delete z by making the parent of z point to NIL
15
15
16
12
10
13
18
delete
6
7
20
z
16
12
23
10
20
18
23
6
7
19
Deletion
Case 2: z has one child
Delete z by making the parent of z point to zs child,
instead of to z
15
5
3
z
16
12
10
6
18
20
20
13
15
delete
12
23
18
23
10
6
7
20
Deletion
Case 3: z has two children
delete
15
z
5
15
16
12
10
y 6
20
13
18
16
12
23
10
20
13
18
23
7
7
21
TREE-DELETE(T, z)
1. if left[z] = NIL or right[z] = NIL
2.
then y z
3.
else y TREE-SUCCESSOR(z)
z has 2 children
4. if left[y] NIL
5.
then x left[y]
6.
else x right[y]
7. if x NIL
8.
15
5
16
12
10
20
13
18
23
6
7
22
TREE-DELETE(T, z) cont.
9. if p[y] = NIL
10.
then root[T] x
11.
else if y = left[p[y]]
14. if y z
16.
16
else right[p[y]] x
13.
15.
then left[p[y]] x
12.
15
12
10
20
13
18
23
6
7
17. return y
24
O(h)
PREDECESSOR
O(h)
SUCCESOR
O(h)
MINIMUM
O(h)
MAXIMUM
O(h)
INSERT
O(h)
DELETE
O(h)