Академический Документы
Профессиональный Документы
Культура Документы
printPreOrder( )
printInOrder( )
printPostOrder( )
size( )
height( )
O(n)
O(n)
O(n)
O(n)
O(n)
O(n)
makeEmpty( )
Lecture 16
Binary Search Trees
CS2134
CS2134
CS2134
7
2
search tree
CS2134
7
2
9
5
1
3
CS2134
7
2
Is 5 equal to 5?
5
1
3
CS2134
7
2
1
3
CS2134
7
2
1
3
CS2134
Is 1 equal to 1?
5
3
2
9
5
10
7
2
Is 5 equal to 5?
3
1
9
3
11
7
2
9
5
4
4
12
Delete 7
Is 7 equal to 7?
7
9
8
8
2
3
4
1
3
13
element
size
left
right
NULL NULL
int main()
{
CS2134
14
15
Search
How do we determine if 5 is in the tree?
Is 5 equal to 7, less than 7?
7
Is 5 equal to 2, less than 2?
2
Is 5 equal to 5?
5
1
3
CS2134
Searching in BSTs
Search for key i in BST
Start at root node,
repeat the following steps until i is found or node is NULL
Compare i to key at current node
if i < key, move on to left child
If i > key, move on to right child
if equal, done
Can do recursively
Faster to do iteratively
Fastest methods are careful to limit # of comparisons
CS2134
7
2
9
21
// Not found
root
t
3
CS2134
6 10
finding 5
// private methods
CS2134
Special Search
Finding the smallest object in the tree
Is left child equal to NULL?
7
Is left child equal to NULL?
2
1
3
CS2134
20
root
return t;
}
9
6
1
CS2134
21
7 10
Special Search
Finding the largest object in the tree
Is right child equal to NULL?
7
9
5
1
3
8
10
CS2134
22
return t;
CS2134
21
1
2
10
Insertion
Insert an object into the tree
If 6 is not in the tree, insert it into the tree
Is 6 equal to 7, less than 7?
7
Is 6 equal to 2, less than 2?
2
1
3
24
inserting 6
t
4t
root
t
6,t
t->size++;
}
6,t
6,t
CS2134
function
call stack
1
2
21
10
BinarySearchTree<int> t;
int NUMS = 10;
const int GAP =
3;
int i, j;
element 3
root
NULL
size
left
right
element 6
element
size
size
left
right
left
right
NULL
element
element
size
size
left
right
left
right
NULL
NULL
size
left
right
size
left
right
NULL
NULL
element
element
element
size
left
right
NULL
NULL NULL
element
size
left
right
NULL NULL
CS2134
26
Deletion
Special Case: Deletion of Smallest object in the Tree
Is left child NULL?
7
9
5
27
Deletion
Special Case: Deletion of Smallest object in the Tree
Is left child NULL?
7
1
2
5
4
28
8
4
1
t->size--;
root
t
9
6
21
CS2134
10