Binary Search Trees (BST'S)
Binary Search Trees (BST'S)
¥
○ Can find location to insert in O(log n) using binary search
○ Check takes O(1) time
○ Insert takes O(n)
● Unsorted array
○ Check takes O(n)
○ Insert is O(1)
struct cell{
}
Data Science Education and Research
int element;
struct cell* leftchild;
struct cell* rightchild;
struct cell* parent;
inorderlistng
: sorted :
www.insofe.edu.in
¥¥ ! £ # ¥
kg
8
Binary search trees (BST’s)
● A binary search tree (BST) is a binary tree which
satisfies the following property (called the BST
property or search property):
÷
Data Science Education and Research www.insofe.edu.in 10
Exercise
● Is the tree below a BST?
320
Id
be
53/20
-
but
" ,
-
int ht -4
-
'
i
Takes
O(h) time
←
E
K
is achievable
¥F¥
Data Science Education and Research www.insofe.edu.in 27
Exercise
● Insert the elements
7, 2, 9, 0, 5, 6, 8, 1
into an initially empty BST. Show the final BST.
¥¥
Data Science Education and Research www.insofe.edu.in 28
Degenerate BST’s
● Insert the elements A zigzag tree:
0,1,2,5,6,7,8,9
into an initially empty BST. Show the final BST.
¥&@⑥÷¥p¥
, ,
→
rotation
la balancing
µ
② operation
moot node is
in
order :
lie / htlrightsvbtreelhtyeftsubtree.tl
Data Science Education and Research
""
www.insofe.edu.in
A
7¥ }
5 ,
CCRS Exl
balanced
O
'
12 6µg
This ( .
height
.
g
-
node is ,
If every
-016gal )
←
,
h ,
then
01h
I \
c- i z
( n >
then :
'
t
o I 61^8
10=1-1B£
-
6
! to
4) ✓ delete 1501
4,9° -7°
-
go
elevate 13
2
I
\g /
13
Tg
,
6
Xp \
7-
●
Complexity of above BST operations is O(h) ¥! ,
I :*
Issue: Height h of BST can be linear in n, and so worst-case running time of BST
operations is O(n)
● Goal: worst-case running time O(log n).
● Solution: balanced BST’s
○ Balanced BST’s (eg AVL trees) have height h=O(log n)
○ A node is balanced if height of its left and right subtrees differ by at most 1
○ After each BST-insert operation, rebalance all nodes in upward path to root using
so-called rotation operations
○ Can prove that if all nodes are balanced then h=O(log n)
Data Science Education and Research www.insofe.edu.in 35
*Dictionary operations in O(log n) time
● Recall that ADT’s are the specs, and data structure is how you do it (implementation)
● Table below gives worst-case performance of various ADT operations for three
different data structure; * denotes the operation is not support by the data structure
ADT operations minheap BST Balanced BST (eg AVL trees)
● Summary: can achieve dictionary operations (insert, search and delete) in O(log n)
time using balanced BST’s.
Data Science Education and Research www.insofe.edu.in 36
References and Acknowledgements
● Many of the examples, images and other content in these slides are taken
(often verbatim) from the following sources:
○ Thomas Cormen, Charles Leiserson, Ronald Rivest, and Clifford Stein,
“Introduction to Algorithms, Third Edition”, MIT Press, 2009.
÷÷¥¥
•
mmds.org
.
www.insofe.edu.in 37