CSCE 3110 Data Structures & Algorithm Analysis: Binary Search Trees Reading: Chap. 4 (4.3) Weiss
CSCE 3110 Data Structures & Algorithm Analysis: Binary Search Trees Reading: Chap. 4 (4.3) Weiss
A Taxonomy of Trees
General Trees any number of children / node
Binary Trees max 2 children / node
Heaps parent < (>) children
Binary Search Trees
Binary Trees
Binary search tree
Every element has a unique key.
The keys in a nonempty left subtree (right subtree)
are smaller (larger) than the key in the root of
subtree.
The left and right subtrees are also binary search
trees.
34
0
34
0
34
0
41
1
41
1
56
2
63
3
72
4
89
5
95
6
56
2
72
4
89
5
56
2
72
4
95
6
95
6
89
41
34
56
72
95
Binary Tree
typedef struct tnode *ptnode;
typedef struct node {
short int key;
ptnode right, left;
};
sample binary search tree code
7
5
4
9
6
10 > 9
10
BST Shapes
removes a specified item from the BST and adjusts the tree
uses a binary search to locate the target item:
starting at the root it probes down the tree till it finds the
target or reaches a leaf node (target not in the tree)
removal of a node must not leave a gap in the tree,
cursor
5
4
Removing 4
replace the link in the
parent with null
9
6
10
7
5
9
6
10
5
4
9
6
5
10
9
8
10
cursor
5
9
6
cursor
10
9
6
10
parent
parent
cursor
cursor
5
4
9
8
5
10
9
8
10
Best Case
BST tree = new BST();
tree.insert
tree.insert
tree.insert
tree.insert
tree.insert
tree.insert
tree.insert
Output:
("E");
("C");
("D");
("A");
("H");
("F");
("K");
>>>> Items in advantageous order:
K
H
F
E
D
C
A
Worst Case
BST tree = new BST();
for (int i = 1; i <= 8; i++)
tree.insert (i);
Output:
Random Case
tree = new BST ();
for (int i = 1; i <= 8; i++)
tree.insert(random());
Output:
Algorithm ?
Running time ?