Binary Search Trees: Tim Doolan
Binary Search Trees: Tim Doolan
Binary Search Trees: Tim Doolan
Tim Doolan
University of Amsterdam
I Resizing Array
I Finding index to insert?
I Insert element at index?
I Linked List
I Insert element into list?
I Finding place to insert?
1 def b i n a r y s e a r c h ( elem , s o r t e d l i s t ) :
2 low , h i g h , h a l f = 0 , l e n ( s o r t e d l i s t ) , 1
3
4 while h a l f > 0 :
5 h a l f = ( h i g h −low ) // 2
6 mid = low + h a l f
7
8 i f elem < s o r t e d l i s t [ mid ] :
9 h i g h = mid
10 e l i f elem > s o r t e d l i s t [ mid ] :
11 low = mid
12 else :
13 r e t u r n mid
14
15 r e t u r n −1
Maintaining a sorted list
I Resizing Array
I Linked List
• Key
• Value
• Left
• Right
• Parent
I No child nodes?
I 1 child node?
I 2 child nodes?
1 def g e t i t h ( r o o t , i ) :
2 i f r o o t . l e f t == None and i == 0 :
3 return root
4
5 s = root . l e f t . size
6 i f s == i :
7 return root
8 elif s > i :
9 return g e t i t h ( root . l e f t , i )
10 else :
11 return g e t i t h ( root . right , i − s − 1 )
Balanced Binary Search Trees
If H = O(log (N))
I All BST functions are O(log (N))
Balanced tree:
I Height of the tree is O(log (N))
AVL Trees
Height augmentation for node n
I -1 if n == None
I 1 + max(n.left.height, n.right.height)
AVL Property:
∀n : |n.balance| ≤ 1