forked from aaronbloomfield/pdr
-
Notifications
You must be signed in to change notification settings - Fork 228
/
05-trees.html
1435 lines (1252 loc) · 53.6 KB
/
05-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">
<title>CS 2150: 05-trees slide set</title>
<meta name="description" content="A set of slides for a course on Program and Data Representation">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="../slides/reveal.js/dist/reset.css">
<link rel="stylesheet" href="../slides/reveal.js/dist/reveal.css">
<link rel="stylesheet" href="../slides/reveal.js/dist/theme/black.css" id="theme">
<link rel="stylesheet" href="../slides/css/pdr.css">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="../slides/reveal.js/plugin/highlight/zenburn.css">
<!-- 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 ) ? '../slides/reveal.js/css/print/pdf.scss' : '../slides/reveal.js/css/print/paper.scss';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="../slides/reveal.js/lib/js/html5shiv.js"></script>
<![endif]-->
<style>.reveal li { font-size:93%; line-height:120%; }</style>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section data-markdown><script type="text/template">
# CS 2150
### Program and Data Representation
<p class='titlep'> </p>
<div class="titlesmall"><p>
<a href="http://www.cs.virginia.edu/~mrf8t">Mark Floryan</a> (mrf8t@virginia.edu)<br>
<a href="http://www.cs.virginia.edu/~asb">Aaron Bloomfield</a> (aaron@virginia.edu)<br>
<a href="http://github.com/uva-cs/pdr">@github</a> | <a href="index.html">↑</a> | <a href="./05-trees.html?print-pdf"><img class="print" width="20" src="../slides/images/print-icon.png" style="top:0px;vertical-align:middle"></a>
</p></div>
<p class='titlep'> </p>
## Trees
</script></section>
<section>
<h2>CS 2150 Roadmap</h2>
<table class="wide">
<tr><td colspan="3"><p class="center">Data Representation</p></td><td></td><td colspan="3"><p class="center">Program Representation</p></td></tr>
<tr>
<td class="top"><small> <br> <br>string<br> <br> <br> <br>int x[3]<br> <br> <br> <br>char x<br> <br> <br> <br>0x9cd0f0ad<br> <br> <br> <br>01101011</small></td>
<!-- image adapted from http://openclipart.org/detail/3677/arrow-left-right-by-torfnase -->
<td><img class="noborder" src="images/red-double-arrow.png" height="500" alt="vertical red double arrow"></td>
<td class="top"> <br>Objects<br> <br>Arrays<br> <br>Primitive types<br> <br>Addresses<br> <br>bits</td>
<td> </td>
<td class="top"><small> <br> <br>Java code<br> <br> <br>C++ code<br> <br> <br>C code<br> <br> <br>x86 code<br> <br> <br>IBCM<br> <br> <br>hexadecimal</small></td>
<!-- image adapted from http://openclipart.org/detail/3677/arrow-left-right-by-torfnase -->
<td><img class="noborder" src="images/green-double-arrow.png" height="500" alt="vertical green double arrow"></td>
<td class="top"> <br>High-level language<br> <br>Low-level language<br> <br>Assembly language<br> <br>Machine code</td>
</tr>
</table>
</section>
<section data-markdown><script type="text/template">
# Contents
[Introduction](#/introduction)
[Binary Search Trees](#/bsts)
[Expression Trees](#/exptrees)
[AVL Trees](#/avltrees)
[Recursion](#/recursion)
[Red-black Trees](#/redblacktrees)
[Splay Trees](#/splaytrees)
[Applications](#/applications)
</script></section>
<section>
<section id="introduction" data-markdown class="center"><script type="text/template">
# Introduction
</script></section>
<section data-markdown><script type="text/template">
## Data Structures
- If we have a good list implementation, do we need any other data structures?
- For computing: ***no***
- We can compute everything with just lists (actually even less). The underlying machine memory can be thought of as a list
- For thinking: ***yes***
- And for organizing the data
- Lists are a very limited way of thinking about problems
</script></section>
<section data-markdown><script type="text/template">
## List Limitations
![list diagram](graphs/list-diagram-1.svg)
- In a list, every element has direct relationships with only two others: the predecessor and the successor
- Access time: Θ(*n*)
- Goal: Θ(log *n*)
</script></section>
<section>
<h2><a href="http://en.wikipedia.org/wiki/File:Tree_of_life_SVG.svg">Complex Relationships: Phylogenetic Tree</a></h2>
<img alt="phylogenetic tree" class="stretch" src="images/05-trees/768px-Tree_of_life_SVG.svg.png" style="background-color:white">
</section>
<section>
<h2><a href="http://commons.wikimedia.org/wiki/File:IndoEuropeanTree.svg">Complex Relationships: Language Tree</a></h2>
<img alt="language tree" class="stretch" src="images/05-trees/IndoEuropeanTree.svg" style="background-color:white">
</section>
<section data-markdown><script type="text/template">
## List → Tree
- List: each element has relationships with up to 2 other elements:
![list diagram](graphs/list-diagram-2.svg)
- Binary Tree: each element has relationships with up to ***3*** other elements
- A tree is a special case of a list
![tree diagram](graphs/tree-diagram.svg)
</script></section>
<section data-markdown><script type="text/template">
## Tree Terms
- *Root*: a node with no parent; there can only be one root
- *Leaf*: a node with no children
- *Siblings*: two nodes with the same parent
- *Height* of a node: length of the ***longest*** path from that node to a leaf
- Thus, all leaves have height of zero
- *Height of a tree*: maximum depth of a node in that tree = height of the root
- *Depth* of a node: length of the path from the root to that node
</script></section>
<section>
<table class="transparent"><tr>
<td class="top" style="width:50%;"><a href="http://commons.wikimedia.org/wiki/File:IndoEuropeanTree.svg"><img src="images/05-trees/IndoEuropeanTree-part.svg" alt="language tree part" style="width:100%;background-color:white"></a></td>
<td class="top" style="width:50%;">
<h2>Tree Terms</h2>
<ul>
<li>Indo-European is the root</li>
<li>Nodes stacked on top of each other are siblings</li>
<li>English is a leaf, and has depth 5<ul class="small">
<li>Depth is the distance to the <i>root</i></li>
<li>English → Old English → Anglo-Frisian → West Germanic → Germaic → Indo-European</li></ul></li>
<li>Germanic is an internal node and has height 6<ul class="small">
<li>Height is the distance to the <i>furthest</i> leaf</li>
<li>Germanic → West Germanic → Low Franconian → West Low Franconian → Old Dutch → Dutch → Afrikaans</li></ul></li>
<li>The tree rooted at Germanic forms a sub-tree of the overall tree</li>
</ul>
</td></tr></table>
</section>
<section data-markdown><script type="text/template">
## More Tree Terms
- *Path*: sequence of nodes *n*<sub>1</sub>, *n*<sub>2</sub>, ..., *n*<sub>*k*</sub> such that *n*<sub>*i*</sub> is parent of *n*<sub>*i*+1</sub> for 1 ≤ *i* ≤ *k*
- *Length*: number of edges in the path
- *Internal path length*: sum of the depths of all the nodes
</script></section>
<section>
<h2>Other Examples of Trees</h2>
<table class="transparent"><tr><td class="top" style="width:60%">
<ul><li>Files and folders on a computer</li>
<li>Compilers: parse tree<pre><code class="avrasm">a = (b+c) * d;</code></pre></li>
<li>Genealogy trees<ul>
<li>These become complicated with some complex family relationships</li></ul></li>
<li>Lab 5: expression trees</li>
</ul>
</td><td class="top" style="width:40%"><img alt="expression tree 1" src="graphs/exp-tree-1.svg"></td>
</tr></table>
</section>
<section>
<h2>First child/next sibling</h2>
<table class="transparent"><tr>
<td class="middle"><pre><code class="avrasm">class TreeNode {
private:
string element;
TreeNode *firstChild;
TreeNode *nextSibling;
public:
// ...
}</code></pre></td>
<td><img alt="file tree 1" src="graphs/file-tree-1.svg"></td>
</tr></table>
</section>
<section data-markdown><script type="text/template">
## Traversals of trees
![expression tree 2](graphs/exp-tree-2.svg)
- Pre-order: `/ * + 1 2 - 3 4 * 5 6`
- In-order: `(((1+2) * (3-4)) / (5*6))`
- Parentheses are added to handle operator precedence issues
- Post-order: `1 2 + 3 4 - * 5 6 * /`
</script></section>
<section data-markdown><script type="text/template">
## Pre-order Traversal
- Pre-order: node first, then children (this is pseudo-code):
```
TreeNode::printTree() {
this.print();
for each child c of this:
c.printTree();
}
```
</script></section>
<section data-markdown><script type="text/template">
## In-order Traversal
- In-order: left node first, then self, then right node (C++):
```
void BST::print(BinaryNode *curNode) {
if (curNode != NULL) {
print(curNode->left);
cout << curNode->element << endl;
print(curNode->right);
}
}
```
</script></section>
<section data-markdown><script type="text/template">
## Post-order Traversal
- Post-order: children first, then node (partly C++, partly pseudo-code):
```
int TreeNode::numNodes(TreeNode *tnode) {
if ( tnode == NULL )
return 0;
else {
sum=0;
for each child c of tnode
sum += numNodes(c);
return 1 + sum;
}
}
```
</script></section>
<section data-markdown><script type="text/template">
## Traversals of trees (again)
![expression tree 2](graphs/exp-tree-2.svg)
- Pre-order: `/ * + 1 2 - 3 4 * 5 6`
- In-order: `(((1+2) * (3-4)) / (5*6))`
- Parentheses are added to handle operator precedence issues
- Post-order: `1 2 + 3 4 - * 5 6 * /`
</script></section>
</section>
<section>
<section id="bsts" data-markdown class="center"><script type="text/template">
# Binary Search Trees
</script></section>
<section>
<h2>Binary Trees</h2>
<table class="transparent"><tr>
<td class="middle" style="width:50%">
<p class="center">All nodes have at most 2 children</p>
<pre><code class="avrasm">class BinaryNode {
public:
// ...
private:
int element;
BinaryNode *left;
BinaryNode *right;
};</code></pre>
<img alt="bst-3" src="graphs/bst-3.svg"></td>
<td style="width:50%"><img alt="bst-1" src="graphs/bst-1.svg"></td>
</tr></table>
</section>
<section>
<h2>Binary Trees: diagram details</h2>
<table class="transparent"><tr>
<td class="top" style="width:60%">
<p>In reality, any child not shown is really a <code>NULL</code> pointer, as shown here; but these are generally omitted from the diagrams</p>
<img alt="bst-4" src="graphs/bst-4.svg"></td>
<td style="width:40%"><img alt="bst-2" src="graphs/bst-2.svg"></td>
</tr></table>
</section>
<section data-markdown><script type="text/template">
## Binary Search Trees (BST)
- Each node has a *key* value that can be compared
- Binary search tree property:
- For a given node, which we will call the *root*...
- Every node in left subtree has a key whose value is *less* than the root's key value, AND
- Every node in right subtree has a key whose value is *greater* than the root's key value
- We assume that duplicate values are not allowed
</script></section>
<section data-markdown><script type="text/template">
## BST: Example
![bst-5](graphs/bst-5.svg)
</script></section>
<section data-markdown><script type="text/template">
## BST: Counter-example
![bst-6](graphs/bst-6.svg)
</script></section>
<section data-markdown><script type="text/template">
## The difference
- Both binary trees and binary search trees have zero, one, or two children per node
- But a binary search tree is *sorted*
- However, most people, when they say "binary tree", really mean a "binary search tree"
- Note that we assume that we can *NOT* have duplicate elements in a BST
</script></section>
<section data-markdown><script type="text/template">
## BST: find
- Basic idea:
- Compare value to be found to key of the root of the tree
- If they are equal, then done
- If not equal, recurse depending on which half of tree the value should be in if it is in tree
- If you hit a `NULL` pointer, then you have "run off" the bottom of the tree, and the value is not in the tree
</script></section>
<section data-markdown><script type="text/template">
## BST: Find
![bst-5](graphs/bst-5.svg)
- Trying to find 3 will go, from the root, left → left → right
- Trying to find 6 will go, from the root, right → left → left
- At that point, we have "run off" the bottom of the tree (via 7's left-child pointer, which is `NULL`), and thus the value is not in the tree
</script></section>
<section data-markdown><script type="text/template">
## BST: find
(no external source code)
```
BinaryNode * BST::find(int x, BinaryNode *curNode) {
// handle case where a NULL pointer could be passed
// curNode->right or curNode->left might be NULL
if (curNode == NULL) // we've "run" off the bottom
return NULL;
else if (x < curNode->element)
return find(x, curNode->left); // search left
else if (x > curNode->element)
return find(x, curNode->right); //search right
else
return curNode; // matched
}
```
</script></section>
<section>
<h2>BST: insert</h2>
<p>Do a find, and when we reach a <code>NULL</code> pointer, create a new node there</p>
<p>(no external source code)</p>
<pre><code>void BST::insert(int x, BinaryNode * & curNode) {
if (curNode==NULL)
curNode = new BinaryNode(x,NULL,NULL);
else if (x < curNode->element)
insert(x, curNode->left);
else if (x > curNode->element)
insert(x, curNode->right);
else
; // duplicate... do nothing
}
</code></pre>
</section>
<section data-markdown><script type="text/template">
## BST: findMax(), findMin()
To find the maximum element in BST, traverse down the right subtree links
![bst-5](graphs/bst-5.svg)
Similarly down the left subttree links for `findMin()`
</script></section>
<section data-markdown><script type="text/template">
## BST: remove
- Disrupts the tree structure
- Basic idea:
- Find node to be removed
- Three cases:
- Node has no children
- Node has one child
- Node has two children
</script></section>
<section>
<h2>BST: remove: no children</h2>
<ul>
<li>Just remove the node (reclaiming memory), adjusting the parent pointer to <code>NULL</code><ul>
<li>In this case, 9's left child link is changed to <code>NULL</code></li></ul></li>
</ul>
<table class="transparent"><tr>
<td class="top"><img alt="bst-7" src="graphs/bst-7.svg"></td>
<td class="middle">→</td>
<td class="top"><img alt="bst-8" src="graphs/bst-8.svg"></td>
</tr></table>
</section>
<section>
<h2>BST: remove: one child</h2>
<ul>
<li>Adjust pointer of parent to point at child, and reclaim memory<ul>
<li>In this case, 4's left pointer is changed to point to 3</li></ul></li>
</ul>
<table class="transparent"><tr>
<td class="top"><img alt="bst-9" src="graphs/bst-9.svg"></td>
<td class="middle">→</td>
<td class="top"><img alt="bst-10" src="graphs/bst-10.svg"></td>
</tr></table>
</section>
<section>
<h2>BST: remove: two children</h2>
<ul>
<li>Replace node with successor, then remove successor from tree<ul>
<li>This requires running <code>findMin()</code> on the right sub-tree, and then removing that element</li>
<li>In this case, 5 is replaced by 7 (and the node that had 7 is removed)</li>
</ul></li></ul>
<table class="transparent"><tr>
<td class="top"><img alt="bst-11" src="graphs/bst-11.svg"></td>
<td class="middle">→</td>
<td class="top"><img alt="bst-12" src="graphs/bst-12.svg"></td>
</tr></table>
</section>
<section>
<h2>BST Height</h2>
<table class="transparent"><tr><td class="top" style="width:50%;">
<ul><li><i>n</i>-node BST: Worst case depth is <i>n</i>-1</li>
<li>This can easily happen if the data to be inserted is already sorted</li>
<li>Claim: The maximum number nodes in a binary tree of height <i>h</i> is 2<sup><i>h</i>+1</sup>-1</li></ul></td>
<td style="width:50%;"><img alt="bst-1" src="graphs/bst-1.svg"></td></tr></table>
</section>
<section data-markdown><script type="text/template">
## Proof by Induction on *h*
- Claim: max nodes in a binary tree of height *h* is 2<sup>*h*+1</sup>-1
- Or: *n* ≤ 2<sup>*h*+1</sup>-1
- For *h*=0: number of nodes is 2<sup>0+1</sup>-1 = 1
- Assume the claim is true for any tree of height *h*
- This would mean *n* ≤ 2<sup>*h*+2</sup>-1 for a tree of height *h*+1
- A tree of height *h*+1 can have 2 subtrees of height *h*; each subtree has 2<sup>*h*+1</sup>-1 nodes; add one for the root
- Thus, our new tree of height *h*+1 has:
- 2(2<sup>*h*+1</sup>-1)+1 = 2<sup>*h*+2</sup>-1 nodes
- If we put *h*+1 into our inductive hypothesis (instead of *h*), we get the same value; thus, it is proven
</script></section>
<section data-markdown><script type="text/template">
## Relationship between *h* and *n*
- Given *n* nodes and height *h*, then by the claim (proven on the previous slide): *n* ≤ 2<sup>*h*+1</sup>-1
- We can simplify:
- *n*+1 ≤ 2<sup>*h*+1</sup>
- log<sub>2</sub>(*n*+1) ≤ log<sub>2</sub>(2<sup>*h*+1</sup>)
- log<sub>2</sub>(*n*+1) ≤ *h*+1
- Thus *h* ≥ log<sub>2</sub>(*n*+1)-1
- This means that the "shortest" tree we can achieve for *n* nodes is proportional to the base-2 log of the height
</script></section>
<section data-markdown><script type="text/template">
## Perfect Binary Tree
![bst-13](graphs/bst-13.svg)
- All leaves have the same depth
- And all nodes have zero or two children, but not one
- Number of leaves: 2<sup>*h*</sup>
- Number of nodes: 1 + 2 + 2<sup>2</sup> + 2<sup>3</sup> + ... + 2<sup>*h*</sup> = 2<sup>*h*+1</sup>-1
- Problem: a perfect binary only holds 2<sup>*h*+1</sup>-1 values
- So you can't have 5 values in a perfect binary tree!
</script></section>
</section>
<section>
<section id="exptrees" data-markdown class="center"><script type="text/template">
# Expression Trees
</script></section>
<section data-markdown><script type="text/template">
## Expression Trees
- A way to keep an internal representation of a mathematical equation
- This allows a computer to compute the value of each node
- You will have to do this for [lab 5](../labs/lab05/index.html)
- The lab expression tree only takes in integers as input; the more generalized version presented here includes variables as well
- See the [Wikipedia article on Expression trees](http://en.wikipedia.org/wiki/Expression_tree), specifically the [section on construction of expression trees](http://en.wikipedia.org/wiki/Expression_tree#Construction_of_an_Expression_Tree) (same example as this one)
- Uses a stack!
</script></section>
<section data-markdown><script type="text/template">
## Expression Tree Traversals
![exp-tree-3](graphs/exp-tree-3.svg)
- Infix notation: `(a + ((b+c) * d))`
- For our purposes, we will always place parentheses around all operations, even if they aren't needed
- Postfix notation: `a b c + d * +`
- Prefix notation: `+ a * + b c d`
</script></section>
<section data-markdown><script type="text/template">
## Building an expression tree
- Given an expression in postfix notation, the algorithm to bulid an expression tree is somewhat similar to that to evaluate a postfix expression (from lab 3)
- The algorithm is to read tokens from input:
- If a number or a varaiable, push it on the stack
- If an operator, pop off two values, attach them as children of the operator, and push that back onto the stack
- A proper postfix expression will have only one value in the stack upon completion
</script></section>
<section data-markdown><script type="text/template">
## Example
Consider the postfix expression: a b + c d e + \* \*; the final expression tree is:
![exp tree 10](graphs/exp-tree-ex-10.svg)
</script></section>
<section data-markdown><script type="text/template">
## Example, step 1
- Expression: <font color='red'>a</font> b + c d e + \* \*
- We read a, and push it onto the stack
![exp tree 1](graphs/exp-tree-ex-1.svg)
</script></section>
<section data-markdown><script type="text/template">
## Example, step 2
- Expression: a <font color='red'>b</font> + c d e + \* \*
- We read b, and push it onto the stack
![exp tree 2](graphs/exp-tree-ex-2.svg)
</script></section>
<section data-markdown><script type="text/template">
## Example, step 3
- Expression: a b <font color='red'>+</font> c d e + \* \*
- We read '+', pop off two values (a and b), put them as children of '+', and push the result back the stack
![exp tree 3](graphs/exp-tree-ex-3.svg)
</script></section>
<section data-markdown><script type="text/template">
## Example, step 4
- Expression: a b + <font color='red'>c</font> d e + \* \*
- We read c, and push it onto the stack
![exp tree 4](graphs/exp-tree-ex-4.svg)
</script></section>
<section data-markdown><script type="text/template">
## Example, step 5
- Expression: a b + c <font color='red'>d</font> e + \* \*
- We read d, and push it onto the stack
![exp tree 5](graphs/exp-tree-ex-5.svg)
</script></section>
<section data-markdown><script type="text/template">
## Example, step 6
- Expression: a b + c d <font color='red'>e</font> + \* \*
- We read e, and push it onto the stack
![exp tree 6](graphs/exp-tree-ex-6.svg)
</script></section>
<section data-markdown><script type="text/teplate">
## Example, step 7
- Expression: a b + c d e <font color='red'>+</font> \* \*
- We read '+', pop off two values (d and e), put them as children of '+', and push the result back the stack
![exp tree 7](graphs/exp-tree-ex-7.svg)
</script></section>
<section data-markdown><script type="text/template">
## Example, step 8
- Expression: a b + c d e + <font color='red'>\*</font> \*
- We read '\*', pop off two values ('+' and c), put them as children of '\*', and push the result back the stack
![exp tree 8](graphs/exp-tree-ex-8.svg)
</script></section>
<section data-markdown><script type="text/template">
## Example, step 9
- Expression: a b + c d e + \* <font color='red'>\*</font>
- We read '\*', pop off two values ('\*' and '+'), put them as children of '\*', and push the result back the stack
![exp tree 9](graphs/exp-tree-ex-9.svg)
</script></section>
<section data-markdown><script type="text/template">
## The final result
![exp tree 10](graphs/exp-tree-ex-10.svg)
</script></section>
</section>
<section>
<section id="avltrees" data-markdown class="center"><script type="text/template">
# AVL Trees
</script></section>
<section data-markdown><script type="text/template">
## Animation Tools
- A good AVL tree animation tool is [here](https://www.cs.usfca.edu/~galles/visualization/AVLtree.html)
- We'll be using this website throughout this slide set
</script></section>
<section data-markdown><script type="text/template">
## AVL Trees
- Motivation: to ***guarantee*** Θ(log *n*) running time on find, insert, and remove
- Idea: Keep tree balanced after each operation
- Solution: AVL trees
- Named after the inventors, Adelson-Velskii and Landis
</script></section>
<section data-markdown><script type="text/template">
## AVL Tree Structure Property
For every node in the tree, the *height* of the left and right sub-trees differs at most by 1
</script></section>
<section data-markdown><script type="text/template">
## AVL Tree
![avl tree 1](graphs/avl-tree-1.svg)
</script></section>
<section data-markdown><script type="text/template">
## AVL balance factor
- Each node of a BST holds:
- The data
- Left and right child pointers
- Possibly a parent node pointer
- An AVL tree node also holds a balance factor
- The height of the *right* subtree minus the height of the *left* subtree
- We could have it be left minus right, but the convention in this class is to always have it be right minus left
- Can be computed on the fly, as well, but that's VERY slow, and defeats the purpose of using AVL trees for speed
</script></section>
<section data-markdown><script type="text/template">
## AVL tree balance
- "Balanced" trees
- 0 means balanced
- 1 means the right subtree is one longer than the left subtree
- -1 means the left subtree is one longer than the right subtree
- "Unbalanced" trees
- A balance factor of -2 or 2
- We'll fix the tree
- Will we ever hit -3 or 3?
</script></section>
<section data-markdown><script type="text/template">
## AVL Tree, with balance factors
![avl tree 2](graphs/avl-tree-2.svg)
By definition, a BST is a valid AVL tree if the balance factor for ***EVERY*** node is -1, 0, or 1
</script></section>
<section data-markdown><script type="text/template">
## Not an AVL Tree
![avl tree 3](graphs/avl-tree-3.svg)
Not balanced: height difference greater than 1
</script></section>
<section data-markdown><script type="text/template">
## AVL Trees: find, insert
- find: same as BST find
- insert: same as BST insert, except might need to "fix" the AVL tree after the insert (via rotations)
- Runtime analysis:
- Θ(*d*), where *d* is the depth of the node being found/inserted
- What is the maximum height of an n-node AVL tree?
</script></section>
<section data-markdown><script type="text/template">
## AVL tree operations
- Perform the operation (insert, delete)
- Move back up to the root, updating the balance factors
- Why only those nodes?
- Because those are the only ones who have had their subtrees altered
- Do tree rotations where the balance factors are 2 or -2
</script></section>
<section data-markdown><script type="text/template">
## How many times to "fix" the tree?
- Any single insert will only modify the balance factor by one
- So we fix the lowest off-balance nodes
- Then everything above it is then balanced
- This means that we will have to only look at the bottom two unbalanced nodes
</script></section>
<section data-markdown><script type="text/template">
## AVL insert
- Let *x* be the *deepest* node where imbalance occurs
- Four cases where the insert happened:
1. In the left subtree of the left child of x
2. In the right subtree of the left child of x
3. In the left subtree of the right child of x
4. In the right subtree of the right child of x
- Cases 1 & 4: perform a single rotation
- Cases 2 & 3: perform a double rotation
</script></section>
<section>
<h2>AVL single right rotation</h2>
<table class="transparent"><tr>
<td class="top"><img alt="avl-tree-18" src="graphs/avl-tree-18.svg"></td>
<td class="middle">→</td>
<td class="top"><img alt="avl-tree-19" src="graphs/avl-tree-19.svg"></td>
</tr></table>
<ul>
<li>The node just inserted was node 1 (blue)</li>
<li>The <i><b>lowest</b></i> node, immediately after the insert, with an imbalance is node 3 (red)</li>
<li>Because node 1 is in the "left subtree of the left child" of node 3, this means we need to perform a single right rotation</li>
</ul>
</section>
<section>
<h2>AVL single left rotation</h2>
<table class="transparent"><tr>
<td class="top"><img alt="avl-tree-20" src="graphs/avl-tree-20.svg"></td>
<td class="middle">→</td>
<td class="top"><img alt="avl-tree-19" src="graphs/avl-tree-19.svg"></td>
</tr></table>
<ul>
<li>The node just inserted was node 3 (red)</li>
<li>The <i><b>lowest</b></i> node, immediately after the insert, with an imbalance is node 1 (blue)</li>
<li>Because node 3 is in the "right subtree of the right child" of node 1, this means we need to perform a single left rotation</li>
</ul>
</section>
<section>
<h2>A side-effect of tree rotations</h2>
<table class="transparent"><tr>
<td class="top"><img alt="avl-tree-18" src="graphs/avl-tree-18.svg"></td>
<td class="middle">→</td>
<td class="top"><img alt="avl-tree-19" src="graphs/avl-tree-19.svg"></td>
</tr></table>
<ul>
<li>This is the single right rotation</li>
<li>Note that at least one node moves "up" (depth decreases)<ul>
<li>In this case, nodes 1 and 2 both move up</li></ul></li>
<li>And at least one node moves "down" (depth increases)<ul>
<li>In this case, node 3 moves down</li></ul></li>
<li>Similarly for a left rotation</li>
</ul>
</section>
<section>
<h2>AVL single right rotation: before & after</h2>
<table class="transparent"><tr>
<td><img alt="avl tree 4" src="graphs/avl-tree-4.svg" width="350"></td>
<td class="middle">→</td>
<td class="top"><img alt="avl tree 5" src="graphs/avl-tree-5.svg" width="350"></td>
</tr></table>
<ul>
<li>Node 1 (red) is what is being inserted</li>
<li>The <i><b>lowest</b></i> node with an imbalance is node 5 (balance: -2)</li>
<li>Because the insert was in 5's "left subtree of the left child", we perform a single right rotation on 5 (and its left child, 3)</li>
</ul>
</section>
<section>
<h2>AVL single right rotation: before & after</h2>
<table class="transparent"><tr>
<td><img alt="avl tree 4" src="graphs/avl-tree-4.svg" width="350"></td>
<td class="middle">→</td>
<td class="top"><img alt="avl tree 5" src="graphs/avl-tree-5.svg" width="350"></td>
</tr></table>
<ul>
<li>From the previous slide, we know we perform a single right rotation on 5 (and its left child, 3)</li>
<li>Thus, the two blue nodes are the 'pivots' of the rotation</li>
<li>Note that node 4 changes parents (from 3's right to 5's left)</li>
</ul>
</section>
<section>
<h2>AVL single right rotation: general case</h2>
<table class="transparent"><tr>
<td><img alt="avl tree 6" src="graphs/avl-tree-6.svg"></td>
<td class="middle">→</td>
<td><img alt="avl tree 7" src="graphs/avl-tree-7.svg"></td>
</tr></table>
<p class="center">\( X < b < Y < a < Z \)</p>
<p class="center">The insert is into sub-tree X, increasing its height to <i>h</i>+1</p>
<p class="center">Notice how sub-tree Y changes parent</p>
</section>
<section data-markdown><script type="text/template">
## Right and left rotations
Note that the trees shown are not necessarily AVL trees, but the rotations are correct
[![tree rotation](images/05-trees/Tree_rotation.png)](http://en.wikipedia.org/wiki/File:Tree_rotation.png)
</script></section>
<section>
<h2>Cases 2 & 3: attempt a single rotation</h2>
<table class="transparent"><tr>
<td><img alt="avl tree 8" src="graphs/avl-tree-8.svg"></td>
<td class="middle">→</td>
<td><img alt="avl tree 9" src="graphs/avl-tree-9.svg"></td>
</tr></table>
<p class="center">\( X < b < Y < a < Z \)</p>
<p class="center">The insert is into sub-tree Y, increasing its height to <i>h</i>+1</p>
<p class="center">Failure! b's left subtree has height <i>h</i>+1; right is <i>h</i>+3</p>
</section>
<section>
<h2>Double rotation</h2>
<table class="transparent"><tr>
<td class="top" style="width:60%;">
<ul><li>Node 5 (red) was just inserted</li>
<li>The <i><b>lowest</b></i> node with an imbalance is node 8 (balance factor: -2)<ul>
<li>When discussing these rotations, we will call this the "parent" node</li></ul></li>
<li>Because the insert happened in 8's
"right subtree of the left child", we perform a <i>double</i> rotation</li>
<li>This consists of a single <i>left</i> rotation on the "child" (node 4), followed by a single <i>right</i> rotation on the "parent" (node 8)</li>
</ul></td>
<td class="top" style="width:40%;"><img alt="avl tree 14" src="graphs/avl-tree-14.svg" width="400"></td>
</tr>
<tr><td colspan="2" style="text-align:left;"><ul><li>Note that the two rotations are in different directions!</li></ul></td></tr>
</table>
</section>
<section>
<h2>Double rotation, step 1</h2>
<table class="transparent"><tr>
<td class="top"><img alt="avl tree 10" src="graphs/avl-tree-10.svg" width="400"></td>
<td class="middle">→</td>
<td class="top"><img alt="avl tree 11" src="graphs/avl-tree-11.svg" width="510"></td>
</tr></table>
<p>This is the single left rotation on the "child". The red node is what was inserted; the blue nodes are the 'pivots' of this single left rotation.</p>
</section>
<section>
<h2>Double rotation, step 2</h2>
<table class="transparent"><tr>
<td class="top"><img alt="avl tree 12" src="graphs/avl-tree-12.svg"></td>
<td class="middle">→</td>
<td class="top"><img alt="avl tree 13" src="graphs/avl-tree-13.svg"></td>
</tr></table>
<p>This is the single right rotation on the "parent". The red node is what was inserted; the green nodes are the 'pivots' of this single right rotation.</p>
</section>
<section>
<h2>AVL double rotation: before & after</h2>
<table class="transparent"><tr>
<td class="top"><img alt="avl tree 14" src="graphs/avl-tree-14.svg"></td>
<td class="middle">→</td>
<td class="top"><img alt="avl tree 15" src="graphs/avl-tree-15.svg"></td>
</tr></table>
<p class="center">The red node is what was inserted</p>
</section>
<section>
<h2>AVL double rotation: general case</h2>
<table class="transparent"><tr>
<td><img alt="avl tree 16" src="graphs/avl-tree-16.svg" width="275"></td>
<td class="middle">
<table><tr><td>
<table><tr><td class="middle">→</td><td><img alt="avl tree 17" src="graphs/avl-tree-17.svg"></td></tr></table>
</td></tr><tr><td> </td></tr><tr><td>\( W < b < X < c < Y < a < Z \)</td></tr><tr><td> </td></tr><tr><td>The insert happens into X</td></tr>
<tr><td>Notice sub-trees X <i>and</i> Y change parents</td></tr></table>
</td>
</tr></table>
</section>
<section data-markdown><script type="text/template">
## Ack! Terminology
- Some people will state a 'double left rotation'
- But is that a left-right? Or a right-left?
- We'll call them 'double left-right' and 'double right-left', which specifies the order to perform the operation on the child and then the parent
</script></section>
<section data-markdown><script type="text/template">
## AVL insert, again
- Let *x* be the *deepest* node where imbalance occurs
- Four cases where the insert happened:
1. In the left subtree of the left child of x
2. In the right subtree of the left child of x
3. In the left subtree of the right child of x
4. In the right subtree of the right child of x
- Cases 1 & 4: perform a single rotation
- Cases 2 & 3: perform a double rotation
</script></section>
<section>
<h2>Algorithmic determination of rotation</h2>
<table class="transparent">
<tr>
<td class="top"><img alt="avl tree 21" src="graphs/avl-tree-21.svg"></td>
<td class="top"><img alt="avl tree 22" src="graphs/avl-tree-22.svg"></td>
<td class="top"><img alt="avl tree 23" src="graphs/avl-tree-23.svg"></td>
<td class="top"><img alt="avl tree 24" src="graphs/avl-tree-24.svg"></td>
</tr>
<tr><td>left-left<br>case</td><td>right-right<br>case</td><td>left-right<br>case</td><td>right-left<br>case</td></tr>
<tr><td> </td><td> </td><td> </td><td> </td></tr>
</table>
<ul>
<li>Given the lowest unbalanced node, and the child in the direction of the insert, compare the balance factors</li>
<li>-2/+1 means a double left-right, +2/+1 means a single left, etc.</li>
</ul>
</section>
<section>
<h2><a href="http://en.wikipedia.org/wiki/File:Tree_Rebalancing.gif">All the tree rotations</a></h2>
<img class="stretch" alt="tree rotations" src="images/05-trees/1024px-Tree_Rebalancing.gif">
</section>
<section data-markdown><script type="text/template">
## AVL Tree: Runtime Analysis
- Find: Θ(log *n*) time: height of tree is always Θ(log *n*)
- Insert: Θ(log *n*) time: find() takes Θ(log *n*), then may have to visit every node on the path back up to root to perform up to 2 single rotations
- Remove: Θ(log *n*): left as an exercise
- Print: Θ(*n*): no matter the data structure, it will still take *n* steps to print *n* elements
</script></section>
</section>
<section>
<section id="recursion" data-markdown class="center"><script type="text/template">
# Recursion
</script></section>
<section data-markdown><script type="text/template">
## Sum the numbers from 1 to n
- We can do it iteratively:
```
int sum (int n) {
int s = 0;
for ( int i = 1; i <= n; i++ )
s += i;
return s;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Sum the numbers from 1 to n
- We can do it *recursively*:
```
int sum (int n) {
return n + sum (n-1);
}
```
What problems arise?
</script></section>
<section data-markdown><script type="text/template">
## Recursion
- Recursion always needs three things to work:
- A way to make the problem *simpler* or smaller
- A way to *detect* when it should terminate or end
- A way to *terminate* or end
- The last example didn't end (among other issues)
</script></section>
<section data-markdown><script type="text/template">
## Sum the numbers from 1 to n
- We can do it *recursively*, but right this time:
```
unsigned int sum (unsigned int n) {
if ( n == 0 )
return 0;
else
return n + sum (n-1);
}
```
- Making the problem simpler is the `sum(n-1)`
- Detecting when to end is the `if (n==0)`
- Termination is the `return 0`
</script></section>
<section data-markdown><script type="text/template">
## Factorial via recursion
- We can do factorial recursively also:
```
unsigned long fact (unsigned long n) {
if ( n == 0 )
return 1;
else
return n * fact (n-1);
}
```
- Making the problem simpler is the `fact(n-1)`
- Detecting when to end is the `if (n==0)`
- Termination is the `return 1`
</script></section>
<section data-markdown><script type="text/template">
## Recursion: pros and cons
- Pros
- It's a more natural way to think of the problem, as you only focus on that one "instance"
- Some problems work well with recursion, but not with iteration (such as tree traversals)
- Cons
- Invoking a subroutine at each step slows performance
- We'll see a way to solve that shortly...
</script></section>
<section data-markdown><script type="text/template">
## Recursion: Fibonacci sequence