Professional Documents
Culture Documents
Binary Search Tree
Binary Search Tree
Speaker
Outline
Introduction
Operations
Conclusion
Introduction
What
sa
It
sa
binary tree !
For each node in a BST, the left subtree is
smaller than it; and the right subtree is
greater than it.
Introduction
This
is a simple BST
10
7
6
13
9
12
14
Introduction
Is
this a BST ?
NO! Because 24 is
less than 25
25
19
8
27
22
24
31
Introduction
Node
structure
Parent
Key
Left
Right
Operations
There
QUERY
INSERT
DELETE
Operation - Query
The
into
Search
Max/Min
Successor/Predecessor
Operation - Search
Search(T,k)
search
Operation - Search
K=12
10
smaller
greater
7
6
13
9
12
14
Operation - Search
K=12
?
10
7
6
smaller
12
13
greater
14
Operation - Search
10
7
6
13
9
12
14
K=12
Operation - Search
Search
Operation Min/Max
For
Operation Predecessor/Successor
Successor(x)
If
Operation Predecessor/Successor
Find
Successor
if Right(x) exists,
// Step 1
then return Min( Right(x) ) ;
else
// Step 2
Find the first ancestor of x whose left
subtree contains x ;
Operation Predecessor/Successor
Step1:
Min
Operation Predecessor/Successor
Step2:
Finding the
ancestor whose
left subtree
contains X
Operation - Insert
Insert(T,z)
Insert
Operation - Insert
Step1:
Step2:
Step3:
Insert z
Operation - Insert
26
30
52
17
24
12
20
44
26
55
Operation - Delete
Delete(T,z)
Delete
Operation - Delete
Case
1: z has no child
55
57
32
25
48
65
Operation - Delete
55
57
32
25
We can simply
remove it from
the tree
48
65
Operation - Delete
Case
32
25
65
48
58
78
Operation - Delete
57
55
32
25
65
48
58
After removing
it, connect it
s
subtree to it
s
parent node
78
Operation - Delete
Case
32
25
61
48
42
46
59
65
Operation - Delete
Find it
s successor
55
32
25
61
48
59
42
46
successor
65
Operation - Delete
z
42
successor
55
32
61
48
25
59
46
What if successor
has two children?
Operation - Delete
What
Operation - Delete
successor
55
42
32
61
48
25
46
59
65
Operation - Delete
Operation - Delete
Operation - Delete
The
25 32 42 46 48 55 59 61 65
After
deleting 32
25 42 46 48 55 59 61 65
Conclusion
If
Conclusion
The
Search time:
BST
O(h)
Array
O(log n)
Conclusion
We
n
A skew binary
search tree
Conclusion
So
Easier
insertion/deletion
And with some optimization, we can avoid
the worst case !