-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsa_16_aa_rb_trees.html
1028 lines (948 loc) · 42.4 KB
/
dsa_16_aa_rb_trees.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="css/fontawesome-free-6.2.1-web/css/all.css" rel="stylesheet">
<script src="lib/colorbrewer.v1.min.js" charset="utf-8"></script>
<script src="lib/colorStringStandalone.js" charset="utf-8"></script>
<script type="text/javascript" src="lib/jquery-2.2.4.min.js"></script>
<title>Design & Analysis: Algorithms</title>
<meta name="description" content="CS4851/6851 GSU class">
<meta name="author" content="Sergey M Plis">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="stylesheet" href="dist/reset.css">
<link rel="stylesheet" href="dist/reveal.css">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="plugin/highlight/monokai.css" id="highlight-theme">
<!-- <link rel="stylesheet" href="lib/css/zenburn.css"> -->
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="dist/theme/aml.css" id="theme">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.scss';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<script type="module" src="js/wc_code/wc-code.js"></script>
<!--Popup Window CSS-->
<style media="screen">
*,*:before,*:after{
padding: 0;
margin: 0;
box-sizing: border-box;
}
.popup{
background-color: #fdf6e3;
width: 80%;
padding: 30px 40px;
position: absolute;
transform: translate(-50%,-50%);
left: 50%;
top: 50%;
border-radius: 8px;
font-family: "Poppins",sans-serif;
display: none;
z-index: 1000;
text-align: left;
max-height: 90%;
overflow: scroll;
}
.popup button{
display: block;
margin: 0 0 20px auto;
background-color: transparent;
font-size: 30px;
color: #fdf6e3;
background: #03549a;
border-radius: 100%;
width: 40px;
height: 40px;
border: none;
outline: none;
cursor: pointer;
}
</style>
</head>
<body>
<div class="popup" id="div4code.1">
<!-- <button id="close">×</button> -->
<wc-code-zone mode="python">
<wc-code style="font-size: 14pt;" theme="monokai" mode="python" file-name="python-file.py">
<script type="wc-content">
class Node:
parent = None
lft = None
rgt = None
def __init__(self, key, val):
self.key = key
self.val = val
def insert(node, key, val):
if node is None: return Node(key, val) # Empty leaf: Add node here
if node.key == key: node.val = val # Found key: Replace val
elif key < node.key: # Less than the key?
node.lft = insert(node.lft, key, val) # Go left
node.lft.parent = node # and the parent
else: # Otherwise...
node.rgt = insert(node.rgt, key, val) # Go right
node.rgt.parent = node # and the parent
return node
def search(node, key):
if node is None: raise KeyError # Empty leaf: It`s not here
if node.key == key: return node # Found key: Return val
elif key < node.key: # Less than the key?
return search(node.lft, key) # Go left
else: # Otherwise...
return search(node.rgt, key) # Go right
class Tree: # Simple wrapper
root = None
def __setitem__(self, key, val):
self.root = insert(self.root, key, val)
def __getitem__(self, key):
return search(self.root, key)
def __contains__(self, key):
try: search(self.root, key)
except KeyError: return False
return True
def inorder_tree_walk(node):
if node is not None:
inorder_tree_walk(node.lft)
print(node.key)
inorder_tree_walk(node.rgt)
def tree_min(node):
while node.lft is not None:
node = node.lft
return node
def tree_max(node):
while node.rgt is not None:
node = node.rgt
return node
def successor(node):
if node.rgt is not None:
return tree_min(node.rgt)
p = node.parent
while p is not None and p.rgt is node:
node = p
p = node.parent
return p
def predecessor(node):
if node.lft is not None:
return tree_max(node.lft)
p = node.parent
while p is not None and p.lft is node:
node = p
p = node.parent
return p
def transplant(tree, u, v):
if u.parent is None:
tree.root = v
elif u is u.parent.lft:
u.parent.lft = v
else:
u.parent.rgt = v
if v is not None:
v.parent = u.parent
def tree_delete(tree, node):
if node.lft is None:
tree_transplant(tree, node, node.rgt)
elif node.rgt is None:
tree_transplant(tree, node, node.lft)
else:
y = tree_min(node.rgt)
if y is not node.rgt:
tree_transplant(tree, y, y.rgt)
y.rgt = node.rgt
y.rgt.parent = y
tree_transplant(tree, node, y)
y.lft = node.lft
y.lft.parent = y
def print2DUtil(node, space, COUNT=10):
if node is None:
return
space += COUNT
print2DUtil(node.rgt, space, COUNT=COUNT)
prefix = ''.join(['.']*(space-COUNT))
print(prefix + str(node.key))
print2DUtil(node.lft, space, COUNT=COUNT)
def print2D(node, COUNT=10):
print2DUtil(node, 0, COUNT=COUNT)
t = Tree()
t[8] = 8
t[4] = 4
t[12] = 12
t[2] = 2
t[6] = 6
t[10] = 10
t[14] = 14
t[1] = 1
t[3] = 3
t[5] = 5
t[7] = 7
t[9] = 9
t[11] = 11
t[13] = 13
t[15] = 15
print2D(t.root)
</script>
</wc-code>
</wc-code-zone>
</div>
<div class="reveal">
<!-- In between the <div="reveal"> and the <div class="slides">-->
<!-- <header style="position: absolute; top: 10px; left: 100px; z-index: 500; font-size:100px;background-color: rgba(0,0,0,0); text-align: center !important"></header> -->
<!-- In between the <div="reveal"> and the <div class="slides">-->
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<section data-background="figures/aatree_examples.svg">
<p>
<h2>Design & Analysis: Algorithms</h2>
<h2>16: Balanced Binary Search Trees</h2>
<h2>Divide & Conquer</h2>
<p>
</section>
<section data-fullscreen>
<h3>Schedule</h3>
<row style="width: 120%">
<col50>
<table style="font-size:16px">
<tr>
<th>#</th>
<th>date</th>
<th>topic</th>
<th>description</th>
</tr>
<tr><td>1</td>
<td> 09-Jan-2023 </td>
<td> Introduction and Introductions </td>
<td> </td>
</tr>
<tr><td>2</td>
<td> 11-Jan-2023 </td>
<td> Basics of Algorithm Analysis </td>
<td> </td>
</tr>
<tr style='background-color: #FBEEC2;'><td> </td><td> 16-Jan-2023 </td><td> <em>Holiday</em> </td><td> </td></tr>
<tr><td> 3 </td><td> 18-Jan-2023 </td><td> Asymptotic Analysis </td><td> hw1 </td></tr>
<tr><td> 4 </td><td> 23-Jan-2023 </td><td> Recurrence Relations: Substitution </td><td> </td></tr>
<tr><td> 5 </td><td> 25-Jan-2023 </td><td> Recursion Trees and the Master Theorem </td><td> </td></tr>
<tr><td> 6 </td><td> 30-Jan-2023 </td><td> Recurrence Relations: Annihilators </td></td></td><td> </td></tr>
<tr><td> 7 </td><td> 1-Feb-2023 </td><td> Recurrence Relations: Transformations </td><td> hw2, hw1 <i class="fa-solid fa-calendar-check"></i> </td></tr>
<tr><td> 8 </td><td> 6-Feb-2023 </td><td> Heap & Invariants</td><td> </td></tr>
<tr><td> 9 </td><td> 8-Feb-2023 </td><td> Queue & Qsort </td><td> </td></tr>
<tr><td> 10 </td><td> 13-Feb-2023 </td><td> Analyzing RQsort </td><td> </td></tr>
<tr><td> 11 </td><td> 15-Feb-2023 </td><td> Comparison-based Sorting Analysis </td><td> hw3, hw2 <i class="fa-solid fa-calendar-check"></i> </td></tr>
<tr><td> 12 </td><td> 20-Feb-2023 </td><td> Dictionary</td><td> </td></tr>
<tr><td> 13 </td><td> 22-Feb-2023 </td><td> Open Address Hashing & Refresher </td><td> </td></tr>
<tr style='background-color: #E5DDCB;'><td> 14 </td><td> 27-Feb-2023 </td><td> Midterm exam </td><td> <em>midpoint</em> </td></tr>
<tr><td> 15 </td><td> 1-Mar-2023 </td><td> Binary Search Trees I </td><td> </td></tr>
<tr><td> 16 </td><td> 6-Mar-2023 </td><td> Binary Search Trees II </td><td>hw4, hw3 <i class="fa-solid fa-calendar-check"></i> </td></tr>
<tr style='background-color: #E0E4CC;'><td> 17 </td><td> 8-Mar-2023 </td><td> Balanced Binary Search Trees </td><td> <i class='fa fa-map-marker' style='color: #FA6900;'></i> </td></tr>
</table>
</col50>
<col50>
<table style="font-size:14px; vertical-align: top;">
<tr>
<th>#</th>
<th>date</th>
<th>topic</th>
<th>description</th>
</tr>
<tr style='background-color: #FBEEC2;'><td> </td><td> 13-Mar-2023 </td><td> <em>Spring Break<em> </td><td> </td></tr>
<tr style='background-color: #FBEEC2;'><td> </td><td> 15-Mar-2023 </td><td> <em>Spring Break<em> </td><td> </td></tr>
<tr><td> 18 </td><td> 20-Mar-2023 </td><td> </td><td>hw5, hw4 <i class="fa-solid fa-calendar-check"></i> </td></tr>
<tr><td> 19 </td><td> 22-Mar-2023 </td><td> </td><td> </td></tr>
<tr><td> 20 </td><td> 27-Mar-2023 </td><td> </td><td> </td></tr>
<tr><td> 21 </td><td> 29-Mar-2023 </td><td> </td><td></td></tr>
<tr><td> 22 </td><td> 3-Apr-2023 </td><td> </td><td> hw6, hw5 <i class="fa-solid fa-calendar-check"></i> </td></tr>
<tr><td> 23 </td><td> 5-Apr-2023 </td><td> </td><td> </td></tr>
<tr><td> 24 </td><td> 10-Apr-2023 </td><td> </td><td> </td></tr>
<tr><td> 25 </td><td> 12-Apr-2023 </td><td> </td><td> hw7, hw6 <i class="fa-solid fa-calendar-check"></i> </td></tr>
<tr><td> 26 </td><td> 17-Apr-2023 </td><td> </td><td> </td></tr>
<tr><td> 27 </td><td> 19-Apr-2023 </td><td> </td><td> </td></tr>
<tr><td> 28 </td><td> 24-Apr-2023 </td><td> </td><td> hw7 <i class="fa-solid fa-calendar-check"></i> </td></tr>
<tr style='background-color: #E5DDCB;'><td> 29 </td><td> 26-Apr-2023 </td><td> Final exam </td><td> </td></tr>
<tr style='color: #ccd5d8ff;'><td> 30 </td><td> 2-May-2022 </td><td> </td><td> </td></tr>
<tr style='color: #ccd5d8ff;'><td> 31 </td><td> 4-May-2022 </td><td> </td><td> </td></tr>
</table>
</col50>
</row>
</section>
<section>
<h3>Outline of the lecture</h3>
<ul>
<li class="fragment roll-in"> AVL tree (the balanced BST)
<li class="fragment roll-in"> 2-3 and 2-3-4 B-trees
<li class="fragment roll-in"> <alert>Red</alert>-<span style="color:#000000;">Black</span> trees emulation of 2-3-4 trees
<li class="fragment roll-in"> AA-trees trees emulation of 2-3 trees
</ul>
</section>
</section>
<section>
<section data-vertical-align-top data-background="figures/random_trees.svg" data-background-size="contain" data-background-transition="zoom">
<h1>AVL tree</h1>
</section>
<section data-vertical-align-top data-background="figures/random_trees.svg" data-background-size="contain" data-background-transition="zoom">
<h2>random binary search trees</h2>
</section>
<section>
<h2>Optimal Binary Trees</h2>
<blockquote style="background-color: #93a1a1; color: #fdf6e3; font-size: 38px; width: 100%; text-align: center;">
All leaf nodes are one level away from each other
</blockquote>
<img src="figures/optimal_bsts.svg" alt="optimal bst" width="100%">
</img>
<div class="fragment roll-in">
A difficult property to maintain
</div>
</section>
<section>
<h2>(self) Balanced Binary Trees</h2>
<blockquote style="background-color: #93a1a1; color: #fdf6e3; font-size: 38px; width: 100%; text-align: center;">
The heights of the left and the right subtrees differ by no more than 1
</blockquote>
$
h(T_r) - h(T_l) \in \{-1, 0, 1\}
$
<img src="figures/balanced_knuth.svg" alt="optimal bst" width="80%">
</img>
</section>
<section>
<row>
<col50>
<img src="figures/Georgy Adelson-Velsky.jpg" alt="Georgy Adelson-Velsky" width="100%">
</img>
<div style="font-size:14pt; margin-top: -25px;">Georgy Adelson-Velsky (1922 - 2014)</div>
</col50>
<col50>
<img src="figures/evgenii_landis.jpg" alt="Georgy Adelson-Velsky" width="48%">
</img>
<div style="font-size:14pt; margin-top: -25px;">Evgenii Landis (1921-1997)</div>
</col50>
</row>
<blockquote style="background-color: #93a1a1; color: #fdf6e3; font-size: 28px; width: 100%; text-align: left;">
In 1962 Georgy <b>A</b>delson-<b>V</b>elsky and Evgenii <b>L</b>andis published a paper <mark>"An algorithm for the organization of information."</mark> which would become the AVL tree, named after it's two inventors. In 1965, Adelson-Velsky headed the <mark>development of a computer chess program</mark> at the Institute for Theoretical and Experimental Physics in Moscow. The program defeated Kotok-McCarthy in the first chess match between computer programs, and evolved into Kaissa, the first world computer chess champion.
</blockquote>
</section>
<section>
<h2>How high can balanced tree get?</h2>
<blockquote style="background-color: #93a1a1; color: #fdf6e3; font-size: 38px; width: 100%; text-align: left;">
Theorem: (Adelson-Velsky & Landis) The height of a balanced binary search tree with $N$ non-leaf nodes is bounded by $\log(N+1)$ from below and $1.4405\log(N+2) - 0.3277$ from above.
</blockquote>
</section>
<section>
<h2>Insertion: case 1</h2>
<row>
<col50>
<h3>before</h3>
<img src="figures/AVL_case1_imbalanced.svg" alt="case 1" width="90%" class="fragment roll-in">
</col50>
<col50>
<h3>after</h3>
<img src="figures/AVL_case1_balanced.svg" alt="case 1" width="90%" class="fragment roll-in">
</col50>
</row>
</section>
<section>
<h2>Insertion: case 2</h2>
<row>
<col50>
<h3>before</h3>
<img src="figures/AVL_case2_imbalanced.svg" alt="case 1" width="90%" class="fragment roll-in">
</col50>
<col50>
<h3>after</h3>
<img src="figures/AVL_case2_balanced.svg" alt="case 1" width="90%" class="fragment roll-in">
</col50>
</row>
</section>
<section>
<h2>Insertion: symmetric cases</h2>
<img src="figures/AVL_symmetric_cases_rotation.svg" alt="symmetric cases" style="margin-top: -40px;" width="90%" class="fragment roll-in">
</section>
<section>
<h2>Empirical analysis</h2>
<ul>
<li class="fragment roll-in"> Consider balanced binary trees with 7 nodes
<li class="fragment roll-in"> 17 trees and $7! = 5040$ ways to build them
<li class="fragment roll-in" style="list-style:none;">
<row>
<col30 class="fragment roll-in">
<img src="figures/2160_balanced_tree.svg" alt="symmetric cases" width="90%">
<div style="font-size:18pt; margin-top: -25px;">appears 2160 times</div>
</col30>
<col30 class="fragment roll-in">
<img src="figures/144_Fib_tree.svg" alt="symmetric cases" width="90%" >
<div style="font-size:18pt; margin-top: -25px;">appears 144 times</div>
</col30>
<col30 class="fragment roll-in">
<img src="figures/216_fiblike_tree.svg" alt="symmetric cases" width="90%">
<div style="font-size:18pt; margin-top: -25px;">appears 216 times</div>
</col30>
</row>
<li class="fragment roll-in"> Empirically established number of comparisons on insertion: $1.01\log N + 0.1$
</ul>
</section>
<section data-vertical-align-top data-background-iframe="https://visualgo.net/en/bst"
data-background-interactive>
<div id="header-left" style="margin-left: -80px; margin-top: 20px">
<img src="figures/AVL_case1_imbalanced.svg" alt="case 1" style="border:0; box-shadow: 0px 0px 0px rgba(150, 150, 255, 1); margin-bottom: -5%" width="160px" >
<div style="font-size:10pt;">case 1</div>
<img src="figures/AVL_case2_imbalanced.svg" alt="case 1" style="border:0; box-shadow: 0px 0px 0px rgba(150, 150, 255, 1); margin-bottom: -5%" width="160px" >
</div>
</section>
<section>
<h2>Implementation</h2>
<row>
<col40>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers="|5|">
class AVLNode:
parent = None
lft = None
rgt = None
lvl = 1 # We've added a level...
def __init__(self, key, val):
self.key = key
self.val = val
</code></pre>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
def avl_height(node):
if node is None: return 0
return node.lvl
</code></pre>
</col40>
<col60>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
def avl_balance(node):
if node is None: return 0
return avl_height(node.lft) - avl_height(node.rgt)
</code></pre>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers="4| ">
class AVLTree: # Simple wrapper
root = None
def __setitem__(self, key, val):
self.root = avl_insert(self.root, key, val)
def __getitem__(self, key):
return search(self.root, key)
def __contains__(self, key):
try: search(self.root, key)
except KeyError: return False
return True
</code></pre>
</col60>
</row>
</section>
<section>
<h2>Rotations</h2>
<row style="margin-top: -100px;">
<col60>
<h2><i class="fa-solid fa-rotate-left"></i></h2>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
def left_rotate(node):
rgt = node.rgt
rgt.parent = node.parent
T2 = rgt.lft
# Perform rotation
rgt.lft = node
node.rgt = T2
node.parent = rgt
# Update heights
node.lvl = 1 + max(avl_height(node.lft),
avl_height(node.rgt))
rgt.lvl = 1 + max(avl_height(rgt.lft),
avl_height(rgt.rgt))
# Return the new root
return rgt
</code></pre>
</col60>
<col60>
<h2><i class="fa-solid fa-rotate-right"></i></h2>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
def right_rotate(node):
lft = node.lft
lft.parent = node.parent
T3 = lft.rgt
# Perform rotation
lft.rgt = node
node.lft = T3
node.parent = lft
# Update heights
node.lvl = 1 + max(avl_height(node.lft),
avl_height(node.rgt))
lft.lvl = 1 + max(avl_height(lft.lft),
avl_height(lft.rgt))
# Return the new root
return lft
</code></pre>
</col60>
</row>
</section>
<section data-vertical-align-top data-background="figures/AVL_rotations_animation.gif" data-background-size="contain" data-background-transition="zoom">
</section>
<section>
<h2><code>avl_insert</code></h2>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
def avl_insert(node, key, val):
# Step 1 - Perform normal BST
if node is None: return AVLNode(key, val)
if node.key == key: node.val = val
elif key < node.key:
node.lft = avl_insert(node.lft, key, val)
else:
node.rgt = avl_insert(node.rgt, key, val)
# Step 2 - Update the height of the
# ancestor node
node.lvl = 1 + max(avl_height(node.lft), avl_height(node.rgt))
# Step 3 - Get the balance factor
balance = avl_balance(node)
# Step 4 - If the node is unbalanced,
# then try out the 4 cases
# Case 1 - Left Left
if balance > 1 and key < node.lft.key:
return right_rotate(node)
# Case 2 - Right Right
if balance < -1 and key > node.rgt.key:
return left_rotate(node)
# Case 3 - Left Right
if balance > 1 and key > node.lft.key:
node.lft = left_rotate(node.lft)
return right_rotate(node)
# Case 4 - Right Left
if balance < -1 and key < node.rgt.key:
node.rgt = right_rotate(node.rgt)
return left_rotate(node)
return node
</code></pre>
</section>
<section data-vertical-align-top data-background="figures/random_trees.svg" data-background-size="contain" data-background-transition="zoom">
<h2>random binary search trees</h2>
</section>
<section data-vertical-align-top data-background="figures/AVL_trees.svg" data-background-size="contain" data-background-transition="zoom">
<h2>random AVL binary search trees</h2>
</section>
<section>
<h2>random AVL BST w/ 1000 nodes</h2>
<img src="figures/AVL_1000.svg" alt="case 1" style="border:0; box-shadow: 0px 0px 0px rgba(150, 150, 255, 1); margin-bottom: -5%; width: 120%;" >
</section>
<section>
<h2>Take Home</h2>
<div style="text-align: left;">
AVL trees are first and one of the simplest self-balancing binary search trees
</div>
<ul>
<li class="fragment roll-in"><b><code>Insert(x)</code></b> - $O(\log n)$ time
<li class="fragment roll-in"><b><code>Lookup(x)</code></b> - $O(\log n)$ time
<li class="fragment roll-in"><b><code>Delete(x)</code></b> - $O(\log n)$ time
<li class="fragment roll-in"><b><code>Merge(x)</code></b> - $O(\log( n + m))$ time
</ul>
</section>
</section>
<section>
<section data-vertical-align-top data-background="figures/pair_up_in_3.png" data-background-size="contain" data-background-transition="zoom">
<h2>2-3 trees</h2>
</section>
<section data-vertical-align-top data-background="figures/2_3_tree_ex1.svg" data-background-size="contain" data-background-transition="slide">
<h2>example 2-3 tree</h2>
<div class='slide-footer' style="text-align: left;">
All leaf nodes occupy the same level
</div>
</section>
<section data-vertical-align-top data-background="figures/2_3_tree_insertion.svg" data-background-size="contain" data-background-transition="slide">
<h2>2-3 tree insertion</h2>
</section>
<section>
<h2>Build your own B-tree</h2>
<div class="slide-footer">
<a href="https://www.cs.usfca.edu/~galles/visualization/BTree.html" target="_blank">If the site does not work: Click here</a>
</div>
</section>
<section>
<h2>2-3 tree emulation</h2>
<img src="figures/2_3_tree_ex1.svg" alt="case 1" style="border:0; box-shadow: 0px 0px 0px rgba(150, 150, 255, 1); margin-top: -4%; width: 120%;" >
<img src="figures/2_3_tree_emulation.svg" alt="case 1" style="border:0; box-shadow: 0px 0px 0px rgba(150, 150, 255, 1); margin-top: -2%; width: 120%;" >
</section>
</section>
<section>
<section data-background="figures/redwood.jpeg">
<h1 style="text-shadow: 4px 4px 4px #002b36; color: #f1f1f1; margin-top: -100px;">Red-Black trees</h1>
</section>
<section>
<h2>Assigned reading</h2>
<row>
<col60>
<img style="border:0; box-shadow: 0px 0px 0px rgba(150, 150, 255, 1);" width="80%"
src="figures/cormen_algs.jpeg" alt="Cormen Algs">
</col60>
<col40>
Read Chapter 13<br>
Red-Black Trees
</col40>
</row>
</section>
<section>
<h2>Red-Black Properties</h2>
<div style="text-align: left;">
A BST is a red-black tree if it satisfies the RB-Properties
</div>
<ol>
<li class="fragment roll-in"> Every node is
either red or black
<li class="fragment roll-in"> The root is black
<li class="fragment roll-in"> Every leaf (NIL) is
black
<li class="fragment roll-in"> If a node is red,
then both its children are black
<li class="fragment roll-in"> For each node, all
paths from the node to descendant leaves contain the same number of
black nodes
</ol>
</section>
<section>
<h2>Left-Rotate</h2>
<ul>
<li class="fragment roll-in">Left-Rotate(x) takes a node x and “rotates” x with its right
child
<li class="fragment roll-in">Right-Rotate is the symmetric operation
<li class="fragment roll-in">Both Left-Rotate and Right-Rotate preserve the BST Property
<li class="fragment roll-in">We’ll use Left-Rotate and Right-Rotate in the RB-Insert procedure
</ul>
</section>
<section data-background="figures/RB_left_right_example.svg" data-background-size="contain" data-vertical-align-top>
<h2>Rotations revisited</h2>
</section>
<section data-background="figures/RB_left_rotation.svg" data-background-size="contain" data-vertical-align-top>
</section>
<section>
<h2>Binary Search Tree Property</h2>
<blockquote style="background-color: #93a1a1; color: #fdf6e3; width:100%; text-align:left;" class="fragment roll-in" >
Let $x$ be a node in a binary search tree. If $y$ is a node in the
left subtree of $x$, then <code>key(y)≤key(x)</code>. If $y$ is a node in the
right subtree of $x$ then <code>key(x)≤key(y)</code>
</blockquote>
</section>
<section>
<h2>In Class Exercise <img style="border:0; box-shadow: 0px 0px 0px rgba(150, 150, 255, 1);" width="100"
src="figures/dolphin_swim.webp" alt="dolphin"></h2>
<div style="text-align: left;">
Show that Left-Rotate(x) maintains the BST Property. In other
words, show that if the BST Property was true for the tree
before the Left-Rotate(x) operation, then it’s true for the tree
after the operation.
</div>
<ul>
<li class="fragment roll-in">Show that after rotation, the BST property holds for the
entire subtree rooted at x
<li class="fragment roll-in">Show that after rotation, the BST property holds for the
subtree rooted at y
<li class="fragment roll-in">Now argue that after rotation, the BST property holds for
the entire tree
</ul>
</section>
<section>
<h2><code>RB-Insert(T,z)</code></h2>
<ol>
<li class="fragment roll-in">Set left(z) and right(z) to be NIL
<li class="fragment roll-in">Let $y$ be the last node processed during a search for $z$ in $T$
<li class="fragment roll-in">Insert $z$ as the appropriate child of $y$ (left child if $key(z)\leq y$, right child otherwise)
<li class="fragment roll-in">Color $z$ red
<li class="fragment roll-in">Call the procedure <code>RB-Insert-Fixup</code>
</ol>
</section>
<section>
<h3><code>RB-Insert-Fixup(T,z)</code></h3>
<pre class="python fragment roll-in" style="width: 99%; font-size: 20pt;"><code data-trim data-noescape data-line-numbers>
def rb_insert_fixup(T, z):
while z.parent.color is red:
if case 1: # z's uncle, y, is red
solve case 1
elif case 2: # z's uncle, y, is black and z is
# a right child
solve case 2
else: # case 3
# z's uncle, y, is black and z is
# a left child
solve case 3
T.root.color = black
</code></pre>
</section>
<section data-vertical-align-top data-background="figures/RB_case_1.svg" data-background-size="contain" data-background-transition="zoom">
<h2>Case 1: $z$'s uncle $y$ is red</h2>
</section>
<section data-vertical-align-top data-background="figures/RB_case23.svg" data-background-size="contain" data-background-transition="zoom">
<h2>Case 2 & 3</h2>
<h3>$z$'s uncle $y$ is black and $z$ is a * child</h3>
</section>
<section>
<h2>Assigned reading</h2>
<row>
<col60>
<img style="border:0; box-shadow: 0px 0px 0px rgba(150, 150, 255, 1);" width="80%"
src="figures/cormen_algs.jpeg" alt="Cormen Algs">
</col60>
<col40>
Read Chapter 13<br>
Red-Black Trees
</col40>
</row>
</section>
</section>
<section>
<section data-vertical-align-top data-background="figures/aatree_examples.svg" data-background-size="contain" data-background-transition="zoom">
<h1>AA Trees</h1>
</section>
<section>
<blockquote style="background-color: #93a1a1; color: #fdf6e3; font-size: 28px; width: 100%; text-align: left;">
AA Tree emulates 2-3 tree. You can think of it as a simpler red-black tree, that is easier to implement and analyze. Introduced by
</blockquote>
Read the paper - it is accessible. I provide the code without proof. Code by <a href="https://folk.idi.ntnu.no/mlh/hetland_org/">Magnus Lie Hetland</a> from his <a href="https://www.amazon.com/Python-Algorithms-Mastering-Basic-Language/dp/148420056X">book</a>.
<div class="slide-footer">
<a href="https://cs.gmu.edu/~rcarver/cs310/aa-tree.pdf">
Andersson, Arne (1993). "Balanced Search Trees made Simple". WADS '93: Proceedings of the Third Workshop on Algorithms and Data Structures. Springer-Verlag: 60–71. ISBN 3540571558.
</a>
</div>
</section>
<section>
<h3>Node and tree classes</h3>
<row style="margin-top: -10px;">
<col60>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
class AANode:
lft = None
rgt = None
lvl = 1 # We've added a level...
def __init__(self, key, val):
self.key = key
self.val = val
</code></pre>
</col60>
<col60>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
class AATree: # Simple wrapper
root = None
def __setitem__(self, key, val):
self.root = aa_insert(self.root, key, val)
def __getitem__(self, key):
return search(self.root, key)
def __contains__(self, key):
try: search(self.root, key)
except KeyError: return False
return True
</code></pre>
</col60>
</row>
<h3>Rebalance operations</h3>
<row style="margin-top: -10px;">
<col60>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
def skew(node): # Basically a right rotation
if None in [node, node.lft]: return node # No need for a skew
if node.lft.lvl != node.lvl: return node # Still no need
lft = node.lft # The 3 steps of the rotation
node.lft = lft.rgt
lft.rgt = node
return lft # Switch pointer from parent
</code></pre>
</col60>
<col60>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
def split(node): # Left rotation & level incr.
if None in [node, node.rgt, node.rgt.rgt]: return node
if node.rgt.rgt.lvl != node.lvl: return node
rgt = node.rgt
node.rgt = rgt.lft
rgt.lft = node
rgt.lvl += 1 # This has moved up
return rgt # This should be pointed to
</code></pre>
</col60>
</row>
</section>
<section>
<h2><code>aa_insert</code></h2>
<pre class="python fragment roll-in" style="width: 99%; font-size: 12pt;"><code data-trim data-noescape data-line-numbers>
def aa_insert(node, key, val):
if node is None: return AANode(key, val)
if node.key == key: node.val = val
elif key < node.key:
node.lft = aa_insert(node.lft, key, val)
else:
node.rgt = aa_insert(node.rgt, key, val)
node = skew(node) # In case it's backward
node = split(node) # In case it's overfull
return node
</code></pre>
<div class="slide-footer">
<a href="#/1/14/0">
Compare with AVL insert
</a> and red-black tree insert implementations
</div>
</section>
<section>
<blockquote style="background-color: #93a1a1; color: #fdf6e3; font-size: 28px; width: 100%; text-align: left;">
The performance of an AA tree is equivalent to the performance of a red–black tree. While an AA tree makes more rotations than a red–black tree, the simpler algorithms tend to be faster, and all of this balances out to result in similar performance. A red–black tree is more consistent in its performance than an AA tree, but an AA tree tends to be flatter, which results in slightly faster search times. <a href="https://en.wikipedia.org/wiki/AA_tree">Wikipedia</a>
</blockquote>
</section>
</section>
<section>
<h2>See you</h2>
Wednesday March $8^{th}$
</section>
</div>
</div>
<script src="dist/reveal.js"></script>
<!-- <link rel="stylesheet" href="lib/css/monokai.css"> -->
<script src="plugin/highlight/highlight.js"></script>
<script src="plugin/math/math.js"></script>
<script src="plugin/chalkboard/plugin.js"></script>
<script src="plugin/notes/notes.js"></script>
<script src="plugin/zoom/zoom.js"></script>
<script src="plugin/menu/menu.js"></script>
<script type="text/javascript">
// Event start load section on slide
Reveal.addEventListener('slidechanged', function(event) {
//-- check if current slide with code
var sectionID = Reveal.getCurrentSlide().id;
if(sectionID === "code.1") {
document.getElementById("div4code.1").style.display = "block";
} else {
document.getElementById("div4code.1").style.display = "none"
}
});
</script>
<script>
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
let notes = document.querySelectorAll('aside.notes');
notes.forEach(n => {
let html = n.innerHTML;
html = html.trim().replace(/\n/g, '<br/>');
n.innerHTML = html;
});
Reveal.initialize({
// history: true,
hash: true,
margin: 0.01,
minScale: 0.01,
maxScale: 1.23,
menu: {
themes: true,
openSlideNumber: true,
openButton: false,
},
customcontrols: {
slideNumberCSS : 'position: fixed; display: block; right: 90px; top: auto; left: auto; width: 50px; bottom: 30px; z-index: 31; font-family: Helvetica, sans-serif; font-size: 12px; line-height: 1; padding: 5px; text-align: center; border-radius: 10px; background-color: rgba(128,128,128,.5)',
controls: [
{ icon: '<i class="fa fa-caret-left"></i>',
css: 'position: fixed; right: 60px; bottom: 30px; z-index: 30; font-size: 24px;',
action: 'Reveal.prev(); return false;'
},
{ icon: '<i class="fa fa-caret-right"></i>',
css: 'position: fixed; right: 30px; bottom: 30px; z-index: 30; font-size: 24px;',
action: 'Reveal.next(); return false;'
}
]
},
chalkboard: {
boardmarkerWidth: 1,
chalkWidth: 2,
chalkEffect: 1,
slideWidth: Reveal.width,
slideHeight: Reveal.height,
toggleNotesButton: false,
toggleChalkboardButton: false,
//src: "chalkboards/chalkboard_em2.json",
readOnly: false,
theme: "blackboard",
eraser: { src: "plugin/chalkboard/img/sponge.png", radius: 30},
},
math: {
mathjax: 'https://cdn.jsdelivr.net/gh/mathjax/mathjax@2.7.8/MathJax.js',
config: 'TeX-AMS_SVG-full',
// pass other options into `MathJax.Hub.Config()`
TeX: {
Macros: {
RR: '\\mathbb{R}',
PP: '\\mathbb{P}',
EE: '\\mathbb{E}',
NN: '\\mathbb{N}',
vth: '\\vec{\\theta}',
loss: '{\\cal l}',
hclass: '{\\cal H}',
CD: '{\\cal D}',
def: '\\stackrel{\\text{def}}{=}',
pag: ['\\text{pa}_{{\cal G}^{#1}}(#2)}', 2],
vec: ['\\boldsymbol{\\mathbf #1}', 1],
set: [ '\\left\\{#1 \\; : \\; #2\\right\\}', 2 ],
bm: ['\\boldsymbol{\\mathbf #1}', 1],
argmin: ['\\operatorname\{arg\\,min\\,\}'],
argmax: ['\\operatorname\{arg\\,max\\,\}'],
prob: ["\\mbox{#1$\\left(#2\\right)$}", 2],
floor: ["\\lfloor #1 \\rfloor",1]
},
loader: {load: ['[tex]/color']},
extensions: ["color.js"],
tex: {packages: {'[+]': ['color']}},
svg: {
fontCache: 'global'
}
}
},
plugins: [ RevealMath, RevealChalkboard, RevealHighlight, RevealNotes, RevealZoom, RevealMenu ],
});
Reveal.configure({ fragments: true }); // set false when developing to see everything at once
Reveal.configure({ slideNumber: true });
//Reveal.configure({ history: true });
Reveal.configure({ slideNumber: 'c / t' });
Reveal.addEventListener( 'darkside', function() {
document.getElementById('theme').setAttribute('href','dist/theme/aml_dark.css');
}, false );
Reveal.addEventListener( 'brightside', function() {
document.getElementById('theme').setAttribute('href','dist/theme/aml.css');
}, false );
</script>
<style type="text/css">
/* 1. Style header/footer <div> so they are positioned as desired. */
#header-left {
position: absolute;
top: 0%;
left: 0%;
}
#header-right {
position: absolute;
top: 0%;
right: 0%;
}
#footer-left {
position: absolute;
bottom: 0%;
left: 0%;
}
</style>