forked from rahuldeve/Diversification-Dataset
-
Notifications
You must be signed in to change notification settings - Fork 0
/
08BinarySearchTrees.txt
1486 lines (846 loc) · 13.9 KB
/
08BinarySearchTrees.txt
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
Binary Search Trees
(cid:1) basic implementations
(cid:1) randomized BSTs
(cid:1) deletion in BSTs
References:
Algorithms in Java, Chapter 12
Intro to Programming, Section 4.4
http://www.cs.princeton.edu/introalgsds/43bst
1
Elementary implementations: summary
implementation
worst case
average case
search
insert
search
insert
ordered
iteration?
operations
on keys
unordered array
N
ordered array
lg N
unordered list
ordered list
N
N
N
N
N
N
N/2
N/2
lg N
N/2
N/2
N
N/2
N/2
no
yes
no
yes
equals()
compareTo()
equals()
compareTo()
Challenge:
Efficient implementations of get() and put() and ordered iteration.
2
(cid:1) basic implementations
(cid:1) randomized BSTs
(cid:1) deletion in BSTs
3
Binary Search Trees (BSTs)
Def. A BINARY SEARCH TREE is a binary tree in symmetric order.
A binary tree is either:
empty
a key-value pair and two binary trees
[neither of which contain that key]
it
best
was
the
of
times
equal keys ruled out to facilitate
associative array implementations
Symmetric order means that:
every node has a key
every nodes key is
larger than all keys in its left subtree
smaller than all keys in its right subtree
node
x
subtrees
smaller
larger
4
BST representation
A BST is a reference to a Node.
A Node is comprised of four fields:
A key and a value.
A reference to the left and right subtree.
smaller keys
larger keys
private class Node
{
Key key;
Value val;
Node left, right;
}
Key and Value are generic types;
Key is Comparable
root
it
2
best
1
was
2
the
1
of
1
times
1
5
BST implementation (skeleton)
public class BST<Key extends Comparable<Key>, Value>
implements Iterable<Key>
{
private Node root;
instance variable
inner class
private class Node
{
Key key;
Value val;
Node left, right;
Node(Key key, Value val)
{
this.key = key;
this.val = val;
}
}
public void put(Key key, Value val)
// see next slides
public Val get(Key key)
// see next slides
}
6
BST implementation (search)
public Value get(Key key)
{
Node x = root;
while (x != null)
{
int cmp = key.compareTo(x.key);
if (cmp == 0) return x.val;
else if (cmp < 0) x = x.left;
else if (cmp > 0) x = x.right;
}
return null;
}
root
it
2
best
1
was
2
the
1
get(the)
returns 1
of
1
times
1
get(worst)
returns null
7
BST implementation (insert)
public void put(Key key, Value val)
{ root = put(root, key, val); }
root
best
1
it
2
was
2
put(the, 2)
overwrites the 1
the
1
worst
1
Caution: tricky recursive code.
Read carefully!
of
1
times
1
put(worst, 1)
adds a new entry
private Node put(Node x, Key key, Value val)
{
if (x == null) return new Node(key, val);
int cmp = key.compareTo(x.key);
if (cmp == 0) x.val = val;
else if (cmp < 0) x.left = put(x.left, key, val);
else if (cmp > 0) x.right = put(x.right, key, val);
return x;
}
8
BST: Construction
Insert the following keys into BST. A S E R C H I N G X M P L
9
Tree Shape
Tree shape.
Many BSTs correspond to same input data.
Cost of search/insert is proportional to depth of node.
typical
A
S
R
E
C
H
I
best
C
H
R
A
E
I
S
worst
A
C
E
Tree shape depends on order of insertion
H
I
R
S
10
BST implementation: iterator?
public Iterator<Key> iterator()
{ return new BSTIterator(); }
private class BSTIterator
implements Iterator<Key>
{
BSTIterator()
{ }
E
A
C
public boolean hasNext()
{ }
public Key next()
{ }
}
I
H
R
N
S
11
BST implementation: iterator?
Approach: mimic recursive inorder traversal
public void visit(Node x)
{
if (x == null) return;
visit(x.left)
StdOut.println(x.key);
visit(x.right);
}
E
A
C
Stack contents
I
H
R
N
visit(E)
visit(A)
print A
visit(C)
print C
print E
visit(S)
visit(I)
visit(H)
print H
print I
visit(R)
visit(N)
print N
print R
print S
A
C
E
H
I
N
R
S
E
A E
E
C E
E
S
I S
H I S
I S
S
R S
N R S
R S
S
To process a node
follow left links until empty
(pushing onto stack)
pop and process
process node at right link
S
12
BST implementation: iterator
public Iterator<Key> iterator()
{ return new BSTIterator(); }
private class BSTIterator
implements Iterator<Key>
{
private Stack<Node>
stack = new Stack<Node>();
private void pushLeft(Node x)
{
while (x != null)
{ stack.push(x); x = x.left; }
}
BSTIterator()
{ pushLeft(root); }
public boolean hasNext()
{ return !stack.isEmpty(); }
public Key next()
{
Node x = stack.pop();
pushLeft(x.right);
return x.key;
}
}
E
A
C
I
H
R
N
A E
A C E
C E
E H I S
H I S
I N R S
N R S
R S
S
S
13
1-1 correspondence between BSTs and Quicksort partitioning
K
E
C
I
S
T
Q
A
E
M
R
X
L
P
O
no
equal
keys
U
14
BSTs: analysis
Theorem. If keys are inserted in random order, the expected number
of comparisons for a search/insert is about 2 ln N.
(cid:1) 1.38 lg N, variance = O(1)
Proof: 1-1 correspondence with quicksort partitioning
Theorem. If keys are inserted in random order, height of tree
is proportional to lg N, except with exponentially small probability.
mean (cid:1) 6.22 lg N, variance = O(1)
But... Worst-case for search/insert/height is N.
e.g., keys inserted in ascending order
15
Searching challenge 3 (revisited):
Problem: Frequency counts in Tale of Two Cities
Assumptions: book has 135,000+ words
about 10,000 distinct words
Which searching method to use?
1) unordered array
2) unordered linked list
3) ordered array with binary search
4) need better method, all too slow
5) doesnt matter much, all fast enough
6) BSTs
insertion cost < 10000 * 1.38 * lg 10000 < .2 million
lookup cost < 135000 * 1.38 * lg 10000 < 2.5 million
16
Elementary implementations: summary
implementation
guarantee
average case
search
insert
search
insert
ordered
iteration?
operations
on keys
unordered array
N
ordered array
lg N
unordered list
ordered list
BST
N
N
N
N
N
N
N
N
N/2
lg N
N/2
N/2
N/2
N/2
N
N/2
1.38 lg N 1.38 lg N
no
yes
no
yes
yes
equals()
compareTo()
equals()
compareTo()
compareTo()
Next challenge:
Guaranteed efficiency for get() and put() and ordered iteration.
17
(cid:1) basic implementations
(cid:1) randomized BSTs
(cid:1) deletion in BSTs
18
Rotation in BSTs
Two fundamental operations to rearrange nodes in a tree.
maintain symmetric order.
local transformations (change just 3 pointers).
basis for advanced BST algorithms
Strategy: use rotations on insert to adjust tree shape to be more balanced
u
v
h
A
B
C
h = rotL(u)
h = rotR(v)
h
v
C
B
u
A
Key point: no change in search code (!)
19
Rotation
Fundamental operation to rearrange nodes in a tree.
easier done than said
raise some nodes, lowers some others
root = rotL(A)
private Node rotL(Node h)
{
Node v = h.r;
h.r = v.l;
v.l = h;
return v;
}
private Node rotR(Node h)
{
Node u = h.l;
h.l = u.r;
u.r = h;
return u;
}
A.left = rotR(S)
20
Recursive BST Root Insertion
insert G
Root insertion: insert a node and make it the new root.
Insert as in standard BST.
Rotate inserted node to the root.
Easy recursive implementation
Caution: very tricky recursive
code.
Read very carefully!
private Node putRoot(Node x, Key key, Val val)
{
if (x == null) return new Node(key, val);
int cmp = key.compareTo(x.key);
if (cmp == 0) x.val = val;
else if (cmp < 0)
{ x.left = putRoot(x.left, key, val); x = rotR(x); }
else if (cmp > 0)
{ x.right = putRoot(x.right, key, val); x = rotL(x); }
return x;
}
21
Constructing a BST with root insertion
Ex. A S E R C H I N G X M P L
Why bother?
Recently inserted keys are near the top (better for some clients).
Basis for advanced algorithms.
22
Randomized BSTs (Roura, 1996)
Intuition. If tree is random, height is logarithmic.
Fact. Each node in a random tree is equally likely to be the root.
Idea. Since new node should be the root with probability 1/(N+1),
make it the root (via root insertion) with probability 1/(N+1).
private Node put(Node x, Key key, Value val)
{
if (x == null) return new Node(key, val);
int cmp = key.compareTo(x.key);
if (cmp == 0) { x.val = val; return x; }
if (StdRandom.bernoulli(1.0 / (x.N + 1.0))
return putRoot(h, key, val);
if (cmp < 0) x.left = put(x.left, key, val);
else if (cmp > 0) x.right = put(x.right, key, val);
x.N++;
return x;
}
need to maintain count of
nodes in tree rooted at x
23
Constructing a randomized BST
Ex: Insert distinct keys in ascending order.
Surprising fact:
Tree has same shape as if keys were
inserted in random order.
Random trees result from any insert order
Note: to maintain associative array abstraction
need to check whether key is in table and replace
value without rotations if that is the case.
24
Randomized BST
Property. Randomized BSTs have the same distribution as BSTs under
random insertion order, no matter in what order keys are inserted.
Expected height is ~6.22 lg N
Average search cost is ~1.38 lg N.
Exponentially small chance of bad balance.
Implementation cost. Need to maintain subtree size in each node.
25
Summary of symbol-table implementations
implementation
guarantee
average case
search
insert
search
insert
ordered
iteration?
operations
on keys
unordered array
N
ordered array
lg N