-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathavl-tree.html
More file actions
1642 lines (1273 loc) · 82.6 KB
/
avl-tree.html
File metadata and controls
1642 lines (1273 loc) · 82.6 KB
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>
<title>AVL Tree</title>
<!-- Google tag (gtag.js) -->
<script async="" src="https://www.googletagmanager.com/gtag/js?id=G-HCERBDV76D"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-HCERBDV76D');
</script>
<meta content="B0487B46A104E90209E8A3BEA24ECA0E" name="msvalidate.01"/>
<meta content="f044b3a12c7918f1" name="yandex-verification"/>
<!--end-->
<meta content="learn about data types, variables, lists, tuples, dictionaries,if else,DSA,loops,user-defined functions, oop, threading and scripting." name="description"/>
<meta content="learnPython" name="author"/>
<meta content="Learn Python for free,learn python for beginners,Core Python,Web frameworks,Multiprocess architecture,Serverside templating language,python tutorials,python4" name="keywords"/>
<meta content="website" property="og:type"/>
<meta content="US-CA" name="”geo.region”"/>
<meta content="353 Jane Stanford Way, Stanford, CA 94305, United States" name="”geo.placename”"/>
<meta content="37.430089898615456;-122.17332683124829" name="”geo.position”"/>
<meta content="37.430089898615456, -122.17332683124829" name="”ICBM”"/>
<link href="https://pythonread.github.io/?m=1" rel="alternate"/>
<link href="/favicon.png" rel="icon"/>
<meta charset="utf-8"/>
<meta content="IE=edge" http-equiv="X-UA-Compatible"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<link href="/style1.css" media="all" rel="stylesheet" type="text/css"/>
<link href="/style2.css" media="all" rel="stylesheet" type="text/css"/>
<link href="/style0.css" media="all" rel="stylesheet" type="text/css"/>
<!--<![endif]-->
</head>
<body>
<div class="nav-wrapper">
<div class="container">
<nav>
<div class="logo wave">
<a href="/" id="logo">
Python Tutorial
</a>
</div>
<div class="nav-toggle-icon" id="nav-toggle-icon" onclick="mobileMenu()">
<div class="material-hamburger">
<span>
</span>
<span>
</span>
<span>
</span>
</div>
</div>
<div class="menu-wrapper" id="menu-wrapper">
<div class="nav-indicator">
</div>
<ul class="menus">
<li>
<a class="wave" href="/">
Home
</a>
</li>
<li>
<a class="wave" href="/projects.html">
Projects
</a>
</li>
<li>
<a class="wave" href="/free-course.html" target="_blank">
Free Course
</a>
</li>
<li>
<a class="wave" href="/dsa.html">
DSA
</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
<div class="contents contents--neg" style="margin-top: 60px">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="d-flex">
<div class="left-bar d-none d-lg-block">
<div class="card-alt mb-10x">
<h3>Page Index</h3>
<div class="list">
<ul>
<li><a href="/dsa.html#data-structure-1" title="Data Structures (I)">Data Structures
(I)</a></li>
<li><a href="/dsa.html#data-structure-2" title="Data Structures (II)">Data Structures
(II)</a></li>
<li><a href="/dsa.html#tree-1" title="Tree based DSA (I)">Tree based DSA (I)</a></li>
<li><a href="/dsa.html#tree-2" title="Tree based DSA (II)">Tree based DSA (II)</a></li>
<li><a href="/dsa.html#graph" title="Graph Data Structures and Algorithm">Graph based
DSA</a></li>
<li><a href="/dsa.html#sorting-searching" title="Sorting and Searching">Sorting and
Searching</a></li>
<li><a href="/dsa.html#greedy-algorithm" title="Greedy Algorithms">Greedy Algorithms</a>
</li>
<li><a href="/dsa.html#dynamic-programming" title="Dynamic Programming">Dynamic
Programming</a></li>
<li><a href="/dsa.html#other-algorithms" title="Other Algorithms">Other Algorithms</a>
</li>
</ul>
</div>
</div>
</div>
<div class="right-bar">
<!--first part end-------------------------------------------->
<div class="editor-contents">
<h1>AVL Tree</h1>
<p class="editor-contents__short-description">In this tutorial, you will learn what an avl tree is. Also, you will find working examples of various operations performed on an avl tree in C, C++, Java and Python.</p>
<div id="node-1530" class="node node-algorithm clearfix" about="/dsa/avl-tree" typeof="sioc:Item foaf:Document">
<span property="dc:title" content="AVL Tree" class="rdf-meta element-hidden"></span>
<div class="content">
<p id="introduction">AVL tree is a self-balancing binary search tree in which each node maintains extra information called a balance factor whose value is either -1, 0 or +1.</p>
<p>AVL tree got its name after its inventor Georgy Adelson-Velsky and Landis.</p>
<hr><h2 id="balancefactor">Balance Factor</h2>
<p>Balance factor of a node in an AVL tree is the difference between the height of the left subtree and that of the right subtree of that node.</p>
<p>Balance Factor = (Height of Left Subtree - Height of Right Subtree) or (Height of Right Subtree - Height of Left Subtree)</p>
<p>The self balancing property of an avl tree is maintained by the balance factor. The value of balance factor should always be -1, 0 or +1.</p>
<p>An example of a balanced avl tree is:</p>
<figure><img alt="avl tree" src="//cdn.programiz.com/sites/tutorial2program/files/avl-tree-final-tree-1_0_2.png" title="avl tree final" width="300" height="260"><figcaption>Avl tree</figcaption></figure><hr><h2>Operations on an AVL tree</h2>
<p>Various operations that can be performed on an AVL tree are:</p>
<h2 id="rotations">Rotating the subtrees in an AVL Tree</h2>
<p>In rotation operation, the positions of the nodes of a subtree are interchanged.</p>
<p>There are two types of rotations:</p>
<hr><h3>Left Rotate</h3>
<p></p><div class="clearfix"></div><p>In left-rotation, the arrangement of the nodes on the right is transformed into the arrangements on the left node.</p>
<p>Algorithm</p>
<ol><li>Let the initial tree be:
<figure><img alt="left-rotate" src="//cdn.programiz.com/sites/tutorial2program/files/avl-tree_leftrotate-1.png" title="left rotate" width="176" height="208"><figcaption>Left rotate</figcaption></figure></li>
<li>If <var>y</var> has a left subtree, assign <var>x</var> as the parent of the left subtree of <var>y</var>.
<figure><img alt="left-rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_leftrotate-2.png" title="assign x as the parent of the left subtree of y" width="230" height="209"><figcaption>Assign x as the parent of the left subtree of y</figcaption></figure></li>
<li>If the parent of <var>x</var> is <code>NULL</code>, make <var>y</var> as the root of the tree.</li>
<li>Else if <var>x</var> is the left child of <var>p</var>, make <var>y</var> as the left child of <var>p</var>.</li>
<li>Else assign <var>y</var> as the right child of <var>p</var>.
<figure><img alt="left-rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_leftrotate-3.png" title="change the parent of x to that of y" width="200" height="156"><figcaption>Change the parent of x to that of y</figcaption></figure></li>
<li>Make <var>y</var> as the parent of <var>x</var>.
<figure><img alt="left-rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_leftrotate-4.png" title="Assign y as the parent of x." width="200" height="223"><figcaption>Assign y as the parent of x.</figcaption></figure></li>
</ol><hr><h3>Right Rotate</h3>
<p>In left-rotation, the arrangement of the nodes on the left is transformed into the arrangements on the right node.</p>
<ol><li>Let the initial tree be:
<figure><img alt="right-rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_rightrotate-1.png" title="initial tree" width="200" height="224"><figcaption>Initial tree</figcaption></figure></li>
<li>If <var>x</var> has a right subtree, assign y as the parent of the right subtree of <var>x</var>.
<figure><img alt="right-rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_rightrotate-2.png" title="assign y as the parent of the right subtree of x." width="230" height="215"><figcaption>Assign y as the parent of the right subtree of x</figcaption></figure></li>
<li>If the parent of <var>y</var> is <code>NULL</code>, make <var>x</var> as the root of the tree.</li>
<li>Else if <var>y</var> is the right child of its parent <var>p</var>, make <var>x</var> as the right child of <var>p</var>.</li>
<li>Else assign <var>x</var> as the left child of <var>p</var>.
<figure><img alt="right-rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_rightrotate-3.png" title="Assign the parent of y as the parent of x." width="200" height="161"><figcaption>Assign the parent of y as the parent of x.</figcaption></figure></li>
<li>Make <var>x</var> as the parent of <var>y</var>.
<figure><img alt="right-rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_rightrotate-4.png" title="assign x as the parent of y" width="200" height="224"><figcaption>Assign x as the parent of y</figcaption></figure></li>
</ol><hr><h3>Left-Right and Right-Left Rotate</h3>
<p>In left-right rotation, the arrangements are first shifted to the left and then to the right.</p>
<ol><li>Do left rotation on x-y.
<figure><img alt="left-right rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree-leftright-rotate-1.png" title="left rotate x-y" width="450" height="247"><figcaption>Left rotate x-y</figcaption></figure></li>
<li>Do right rotation on y-z.
<figure><img alt="left-right rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree-leftright-rotate-2.png" title="right rotate z-y" width="450" height="233"><figcaption>Right rotate z-y</figcaption></figure></li>
</ol><p>In right-left rotation, the arrangements are first shifted to the right and then to the left.</p>
<ol><li>Do right rotation on x-y.
<figure><img alt="right-left rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree-rightleft-rotate-1.png" title="right rotate x-y" width="450" height="240"><figcaption>Right rotate x-y</figcaption></figure></li>
<li>Do left rotation on z-y.
<figure><img alt="right-left rotate" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree-rightleft-rotate-2.png" title="left rotate z-y" width="450" height="235"><figcaption>Left rotate z-y</figcaption></figure></li>
</ol><hr><h2 id="insertion">Algorithm to insert a newNode</h2>
<p>A <var>newNode</var> is always inserted as a leaf node with balance factor equal to 0.</p>
<ol><li>Let the initial tree be:
<figure><img alt="initial tree" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_initial-tree.png" title="initial tree for insertion" width="450" height="325"><figcaption>Initial tree for insertion</figcaption></figure><br>
Let the node to be inserted be:
<figure><img alt="new node" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_newnode.png" title="new node" width="130" height="145"><figcaption>New node</figcaption></figure></li>
<li>Go to the appropriate leaf node to insert a <var>newNode</var> using the following recursive steps. Compare <var>newKey</var> with <var>rootKey</var> of the current tree.
<ol type="a"><li>If <var>newKey</var> < <var>rootKey</var>, call insertion algorithm on the left subtree of the current node until the leaf node is reached.</li>
<li>Else if <var>newKey</var> > <var>rootKey</var>, call insertion algorithm on the right subtree of current node until the leaf node is reached.</li>
<li>Else, return <var>leafNode</var>.
<figure><img alt="avl tree insertion" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_find-position.png" title="finding the location to insert newNode" width="500" height="275"><figcaption>Finding the location to insert newNode</figcaption></figure></li>
</ol></li>
<li>Compare <var>leafKey</var> obtained from the above steps with <var>newKey</var>:
<ol type="a"><li>If <var>newKey</var> < <var>leafKey</var>, make newNode as the <var>leftChild</var> of <var>leafNode</var>.</li>
<li>Else, make <var>newNode</var> as rightChild of <var>leafNode</var>.
<figure><img alt="avl tree insertion" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_insert.png" title="inserting the new node" width="450" height="364"><figcaption>Inserting the new node</figcaption></figure></li>
</ol></li>
<li>Update <var>balanceFactor</var> of the nodes.
<figure><img alt="avl tree insertion" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_update-bf.png" title="updating the balance factor after insertion" width="400" height="355"><figcaption>Updating the balance factor after insertion</figcaption></figure></li>
<li>If the nodes are unbalanced, then rebalance the node.
<ol type="a"><li>If <var>balanceFactor</var> > 1, it means the height of the left subtree is greater than that of the right subtree. So, do a right rotation or left-right rotation
<ol type="i"><li>If <var>newNodeKey</var> < <var>leftChildKey</var> do right rotation.</li>
<li>Else, do left-right rotation.
<figure><img alt="insertion in avl tree" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_balance1.png" title="balancing the tree with rotation" width="1200" height="460"><figcaption>Balancing the tree with rotation</figcaption></figure><figure><img alt="insertion in avl tree" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_balnce2.png" title="balancing the tree with rotation" width="1200" height="468"><figcaption>Balancing the tree with rotation</figcaption></figure></li>
</ol></li>
<li>If <var>balanceFactor</var> < -1, it means the height of the right subtree is greater than that of the left subtree. So, do right rotation or right-left rotation
<ol type="i"><li>If <var>newNodeKey</var> > <var>rightChildKey</var> do left rotation.</li>
<li>Else, do right-left rotation</li>
</ol></li>
</ol></li>
<li>The final tree is:
<figure><img alt="left-right insertion" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_final-tree.png" title="final balanced tree" width="400" height="293"><figcaption>Final balanced tree</figcaption></figure></li>
</ol><hr><h2 id="deletion">Algorithm to Delete a node</h2>
<p>A node is always deleted as a leaf node. After deleting a node, the balance factors of the nodes get changed. In order to rebalance the balance factor, suitable rotations are performed.</p>
<ol><li>Locate <var>nodeToBeDeleted</var> (recursion is used to find <var>nodeToBeDeleted</var> in the code used below).
<figure><img alt="node to be deleted" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_nodeToBeDeleted_0.png" title="locating the node to be deleted" width="400" height="293"><figcaption>Locating the node to be deleted</figcaption></figure></li>
<li>There are three cases for deleting a node:
<ol type="a"><li>If <var>nodeToBeDeleted</var> is the leaf node (ie. does not have any child), then remove <var>nodeToBeDeleted</var>.</li>
<li>If <var>nodeToBeDeleted</var> has one child, then substitute the contents of <var>nodeToBeDeleted</var> with that of the child. Remove the child.</li>
<li>If <var>nodeToBeDeleted</var> has two children, find the inorder successor <var>w</var> of <var>nodeToBeDeleted</var> (ie. node with a minimum value of key in the right subtree).
<figure><img alt="finding the successor" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_successor_0.png" title="finding the successor" width="400" height="293"><figcaption>Finding the successor</figcaption></figure><ol type="i"><li>Substitute the contents of <var>nodeToBeDeleted</var> with that of <var>w</var>.
<figure><img alt="substitute the node to be deleted" src="https://cdn.programiz.com/sites/tutorial2program/files/avl-tree_substitute_0.png" title="substitute the node to be deleted" width="400" height="258"><figcaption>Substitute the node to be deleted</figcaption></figure></li>
<li>Remove the leaf node <var>w</var>.
<figure><img alt="remove w" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_removal_0.png" title="remove w" width="400" height="293"><figcaption>Remove w</figcaption></figure></li>
</ol></li>
</ol></li>
<li>Update <var>balanceFactor</var> of the nodes.
<figure><img alt="update bf" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree_upatebf_0.png" title="update bf" width="400" height="293"><figcaption>Update bf</figcaption></figure></li>
<li>Rebalance the tree if the balance factor of any of the nodes is not equal to -1, 0 or 1.
<ol type="a"><li>If <var>balanceFactor</var> of <var>currentNode</var> > 1,
<ol type="i"><li>If <var>balanceFactor</var> of <var>leftChild</var> >= 0, do right rotation.
<figure><img alt="right-rotate" src="/sites/tutorial2program/files/avl-tree_balance_0.png" title="right-rotate for balancing the tree" width="700" height="262"><figcaption>Right-rotate for balancing the tree</figcaption></figure></li>
<li>Else do left-right rotation.</li>
</ol></li>
<li>If <var>balanceFactor</var> of <var>currentNode</var> < -1,
<ol type="i"><li>If <var>balanceFactor</var> of <var>rightChild</var> <= 0, do left rotation.</li>
<li>Else do right-left rotation.</li>
</ol></li>
</ol></li>
<li>The final tree is:
<figure><img alt="avl tree" src="https://www.programiz.com/sites/tutorial2program/files/avl-tree-final-tree-1_0_2.png" title="avl tree final" width="300" height="260"><figcaption>Avl tree final</figcaption></figure></li>
</ol><hr><h2 id="code">Python, Java and C/C++ Examples</h2>
<div class="tabbed-editor">
<div id="py1" onclick="changepy()" class="tabbed-editor__node tabbed-editor__node--active"><a href="#python-code">Python</a></div>
<div id="java1" onclick="changejava()" class="tabbed-editor__node"><a href="#java-code">Java</a></div>
<div id="c1" onclick="changec()" class="tabbed-editor__node"><a href="#c-code">C</a></div>
<div id="cpp1" onclick="changecpp()" class="tabbed-editor__node"><a href="#cpp-code">C++</a></div>
</div>
<div class="code-editor code-editor--tabbed">
<div class="code-editor__area code-editor__area--active" id="python-code">
<div class="pre-code-wrapper"><div title="Click to copy" class="copy-code-button"></div><pre class="exec" style="max-height: 600px;"><code class="python hljs"><span class="hljs-comment"># AVL tree implementation in Python</span>
<span class="hljs-keyword">import</span> sys
<span class="hljs-comment"># Create a tree node</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TreeNode</span><span class="hljs-params">(object)</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, key)</span>:</span>
self.key = key
self.left = <span class="hljs-literal">None</span>
self.right = <span class="hljs-literal">None</span>
self.height = <span class="hljs-number">1</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AVLTree</span><span class="hljs-params">(object)</span>:</span>
<span class="hljs-comment"># Function to insert a node</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">insert_node</span><span class="hljs-params">(self, root, key)</span>:</span>
<span class="hljs-comment"># Find the correct location and insert the node</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
<span class="hljs-keyword">return</span> TreeNode(key)
<span class="hljs-keyword">elif</span> key < root.key:
root.left = self.insert_node(root.left, key)
<span class="hljs-keyword">else</span>:
root.right = self.insert_node(root.right, key)
root.height = <span class="hljs-number">1</span> + max(self.getHeight(root.left),
self.getHeight(root.right))
<span class="hljs-comment"># Update the balance factor and balance the tree</span>
balanceFactor = self.getBalance(root)
<span class="hljs-keyword">if</span> balanceFactor > <span class="hljs-number">1</span>:
<span class="hljs-keyword">if</span> key < root.left.key:
<span class="hljs-keyword">return</span> self.rightRotate(root)
<span class="hljs-keyword">else</span>:
root.left = self.leftRotate(root.left)
<span class="hljs-keyword">return</span> self.rightRotate(root)
<span class="hljs-keyword">if</span> balanceFactor < <span class="hljs-number">-1</span>:
<span class="hljs-keyword">if</span> key > root.right.key:
<span class="hljs-keyword">return</span> self.leftRotate(root)
<span class="hljs-keyword">else</span>:
root.right = self.rightRotate(root.right)
<span class="hljs-keyword">return</span> self.leftRotate(root)
<span class="hljs-keyword">return</span> root
<span class="hljs-comment"># Function to delete a node</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">delete_node</span><span class="hljs-params">(self, root, key)</span>:</span>
<span class="hljs-comment"># Find the node to be deleted and remove it</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
<span class="hljs-keyword">return</span> root
<span class="hljs-keyword">elif</span> key < root.key:
root.left = self.delete_node(root.left, key)
<span class="hljs-keyword">elif</span> key > root.key:
root.right = self.delete_node(root.right, key)
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">if</span> root.left <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
temp = root.right
root = <span class="hljs-literal">None</span>
<span class="hljs-keyword">return</span> temp
<span class="hljs-keyword">elif</span> root.right <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
temp = root.left
root = <span class="hljs-literal">None</span>
<span class="hljs-keyword">return</span> temp
temp = self.getMinValueNode(root.right)
root.key = temp.key
root.right = self.delete_node(root.right,
temp.key)
<span class="hljs-keyword">if</span> root <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
<span class="hljs-keyword">return</span> root
<span class="hljs-comment"># Update the balance factor of nodes</span>
root.height = <span class="hljs-number">1</span> + max(self.getHeight(root.left),
self.getHeight(root.right))
balanceFactor = self.getBalance(root)
<span class="hljs-comment"># Balance the tree</span>
<span class="hljs-keyword">if</span> balanceFactor > <span class="hljs-number">1</span>:
<span class="hljs-keyword">if</span> self.getBalance(root.left) >= <span class="hljs-number">0</span>:
<span class="hljs-keyword">return</span> self.rightRotate(root)
<span class="hljs-keyword">else</span>:
root.left = self.leftRotate(root.left)
<span class="hljs-keyword">return</span> self.rightRotate(root)
<span class="hljs-keyword">if</span> balanceFactor < <span class="hljs-number">-1</span>:
<span class="hljs-keyword">if</span> self.getBalance(root.right) <= <span class="hljs-number">0</span>:
<span class="hljs-keyword">return</span> self.leftRotate(root)
<span class="hljs-keyword">else</span>:
root.right = self.rightRotate(root.right)
<span class="hljs-keyword">return</span> self.leftRotate(root)
<span class="hljs-keyword">return</span> root
<span class="hljs-comment"># Function to perform left rotation</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">leftRotate</span><span class="hljs-params">(self, z)</span>:</span>
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = <span class="hljs-number">1</span> + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = <span class="hljs-number">1</span> + max(self.getHeight(y.left),
self.getHeight(y.right))
<span class="hljs-keyword">return</span> y
<span class="hljs-comment"># Function to perform right rotation</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">rightRotate</span><span class="hljs-params">(self, z)</span>:</span>
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = <span class="hljs-number">1</span> + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = <span class="hljs-number">1</span> + max(self.getHeight(y.left),
self.getHeight(y.right))
<span class="hljs-keyword">return</span> y
<span class="hljs-comment"># Get the height of the node</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getHeight</span><span class="hljs-params">(self, root)</span>:</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
<span class="hljs-keyword">return</span> root.height
<span class="hljs-comment"># Get balance factore of the node</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getBalance</span><span class="hljs-params">(self, root)</span>:</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
<span class="hljs-keyword">return</span> self.getHeight(root.left) - self.getHeight(root.right)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getMinValueNode</span><span class="hljs-params">(self, root)</span>:</span>
<span class="hljs-keyword">if</span> root <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">or</span> root.left <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
<span class="hljs-keyword">return</span> root
<span class="hljs-keyword">return</span> self.getMinValueNode(root.left)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">preOrder</span><span class="hljs-params">(self, root)</span>:</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
<span class="hljs-keyword">return</span>
<span class="hljs-keyword">print</span>(<span class="hljs-string">"{0} "</span>.format(root.key), end=<span class="hljs-string">""</span>)
self.preOrder(root.left)
self.preOrder(root.right)
<span class="hljs-comment"># Print the tree</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">printHelper</span><span class="hljs-params">(self, currPtr, indent, last)</span>:</span>
<span class="hljs-keyword">if</span> currPtr != <span class="hljs-literal">None</span>:
sys.stdout.write(indent)
<span class="hljs-keyword">if</span> last:
sys.stdout.write(<span class="hljs-string">"R----"</span>)
indent += <span class="hljs-string">" "</span>
<span class="hljs-keyword">else</span>:
sys.stdout.write(<span class="hljs-string">"L----"</span>)
indent += <span class="hljs-string">"| "</span>
<span class="hljs-keyword">print</span>(currPtr.key)
self.printHelper(currPtr.left, indent, <span class="hljs-literal">False</span>)
self.printHelper(currPtr.right, indent, <span class="hljs-literal">True</span>)
myTree = AVLTree()
root = <span class="hljs-literal">None</span>
nums = [<span class="hljs-number">33</span>, <span class="hljs-number">13</span>, <span class="hljs-number">52</span>, <span class="hljs-number">9</span>, <span class="hljs-number">21</span>, <span class="hljs-number">61</span>, <span class="hljs-number">8</span>, <span class="hljs-number">11</span>]
<span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> nums:
root = myTree.insert_node(root, num)
myTree.printHelper(root, <span class="hljs-string">""</span>, <span class="hljs-literal">True</span>)
key = <span class="hljs-number">13</span>
root = myTree.delete_node(root, key)
<span class="hljs-keyword">print</span>(<span class="hljs-string">"After Deletion: "</span>)
myTree.printHelper(root, <span class="hljs-string">""</span>, <span class="hljs-literal">True</span>)</code></pre></div>
</div>
<div class="code-editor__area" id="java-code">
<div class="pre-code-wrapper"><div title="Click to copy" class="copy-code-button"></div><pre class="exec" style="max-height: 600px;"><code class="java hljs"><span class="hljs-comment">// AVL tree implementation in Java</span>
<span class="hljs-comment">// Create node</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span> </span>{
<span class="hljs-keyword">int</span> item, height;
Node left, right;
Node(<span class="hljs-keyword">int</span> d) {
item = d;
height = <span class="hljs-number">1</span>;
}
}
<span class="hljs-comment">// Tree class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AVLTree</span> </span>{
Node root;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">height</span><span class="hljs-params">(Node N)</span> </span>{
<span class="hljs-keyword">if</span> (N == <span class="hljs-keyword">null</span>)
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
<span class="hljs-keyword">return</span> N.height;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">max</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
<span class="hljs-keyword">return</span> (a > b) ? a : b;
}
<span class="hljs-function">Node <span class="hljs-title">rightRotate</span><span class="hljs-params">(Node y)</span> </span>{
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = max(height(y.left), height(y.right)) + <span class="hljs-number">1</span>;
x.height = max(height(x.left), height(x.right)) + <span class="hljs-number">1</span>;
<span class="hljs-keyword">return</span> x;
}
<span class="hljs-function">Node <span class="hljs-title">leftRotate</span><span class="hljs-params">(Node x)</span> </span>{
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = max(height(x.left), height(x.right)) + <span class="hljs-number">1</span>;
y.height = max(height(y.left), height(y.right)) + <span class="hljs-number">1</span>;
<span class="hljs-keyword">return</span> y;
}
<span class="hljs-comment">// Get balance factor of a node</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getBalanceFactor</span><span class="hljs-params">(Node N)</span> </span>{
<span class="hljs-keyword">if</span> (N == <span class="hljs-keyword">null</span>)
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
<span class="hljs-keyword">return</span> height(N.left) - height(N.right);
}
<span class="hljs-comment">// Insert a node</span>
<span class="hljs-function">Node <span class="hljs-title">insertNode</span><span class="hljs-params">(Node node, <span class="hljs-keyword">int</span> item)</span> </span>{
<span class="hljs-comment">// Find the position and insert the node</span>
<span class="hljs-keyword">if</span> (node == <span class="hljs-keyword">null</span>)
<span class="hljs-keyword">return</span> (<span class="hljs-keyword">new</span> Node(item));
<span class="hljs-keyword">if</span> (item < node.item)
node.left = insertNode(node.left, item);
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item > node.item)
node.right = insertNode(node.right, item);
<span class="hljs-keyword">else</span>
<span class="hljs-keyword">return</span> node;
<span class="hljs-comment">// Update the balance factor of each node</span>
<span class="hljs-comment">// And, balance the tree</span>
node.height = <span class="hljs-number">1</span> + max(height(node.left), height(node.right));
<span class="hljs-keyword">int</span> balanceFactor = getBalanceFactor(node);
<span class="hljs-keyword">if</span> (balanceFactor > <span class="hljs-number">1</span>) {
<span class="hljs-keyword">if</span> (item < node.left.item) {
<span class="hljs-keyword">return</span> rightRotate(node);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item > node.left.item) {
node.left = leftRotate(node.left);
<span class="hljs-keyword">return</span> rightRotate(node);
}
}
<span class="hljs-keyword">if</span> (balanceFactor < -<span class="hljs-number">1</span>) {
<span class="hljs-keyword">if</span> (item > node.right.item) {
<span class="hljs-keyword">return</span> leftRotate(node);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item < node.right.item) {
node.right = rightRotate(node.right);
<span class="hljs-keyword">return</span> leftRotate(node);
}
}
<span class="hljs-keyword">return</span> node;
}
<span class="hljs-function">Node <span class="hljs-title">nodeWithMimumValue</span><span class="hljs-params">(Node node)</span> </span>{
Node current = node;
<span class="hljs-keyword">while</span> (current.left != <span class="hljs-keyword">null</span>)
current = current.left;
<span class="hljs-keyword">return</span> current;
}
<span class="hljs-comment">// Delete a node</span>
<span class="hljs-function">Node <span class="hljs-title">deleteNode</span><span class="hljs-params">(Node root, <span class="hljs-keyword">int</span> item)</span> </span>{
<span class="hljs-comment">// Find the node to be deleted and remove it</span>
<span class="hljs-keyword">if</span> (root == <span class="hljs-keyword">null</span>)
<span class="hljs-keyword">return</span> root;
<span class="hljs-keyword">if</span> (item < root.item)
root.left = deleteNode(root.left, item);
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item > root.item)
root.right = deleteNode(root.right, item);
<span class="hljs-keyword">else</span> {
<span class="hljs-keyword">if</span> ((root.left == <span class="hljs-keyword">null</span>) || (root.right == <span class="hljs-keyword">null</span>)) {
Node temp = <span class="hljs-keyword">null</span>;
<span class="hljs-keyword">if</span> (temp == root.left)
temp = root.right;
<span class="hljs-keyword">else</span>
temp = root.left;
<span class="hljs-keyword">if</span> (temp == <span class="hljs-keyword">null</span>) {
temp = root;
root = <span class="hljs-keyword">null</span>;
} <span class="hljs-keyword">else</span>
root = temp;
} <span class="hljs-keyword">else</span> {
Node temp = nodeWithMimumValue(root.right);
root.item = temp.item;
root.right = deleteNode(root.right, temp.item);
}
}
<span class="hljs-keyword">if</span> (root == <span class="hljs-keyword">null</span>)
<span class="hljs-keyword">return</span> root;
<span class="hljs-comment">// Update the balance factor of each node and balance the tree</span>
root.height = max(height(root.left), height(root.right)) + <span class="hljs-number">1</span>;
<span class="hljs-keyword">int</span> balanceFactor = getBalanceFactor(root);
<span class="hljs-keyword">if</span> (balanceFactor > <span class="hljs-number">1</span>) {
<span class="hljs-keyword">if</span> (getBalanceFactor(root.left) >= <span class="hljs-number">0</span>) {
<span class="hljs-keyword">return</span> rightRotate(root);
} <span class="hljs-keyword">else</span> {
root.left = leftRotate(root.left);
<span class="hljs-keyword">return</span> rightRotate(root);
}
}
<span class="hljs-keyword">if</span> (balanceFactor < -<span class="hljs-number">1</span>) {
<span class="hljs-keyword">if</span> (getBalanceFactor(root.right) <= <span class="hljs-number">0</span>) {
<span class="hljs-keyword">return</span> leftRotate(root);
} <span class="hljs-keyword">else</span> {
root.right = rightRotate(root.right);
<span class="hljs-keyword">return</span> leftRotate(root);
}
}
<span class="hljs-keyword">return</span> root;
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">preOrder</span><span class="hljs-params">(Node node)</span> </span>{
<span class="hljs-keyword">if</span> (node != <span class="hljs-keyword">null</span>) {
System.out.print(node.item + <span class="hljs-string">" "</span>);
preOrder(node.left);
preOrder(node.right);
}
}
<span class="hljs-comment">// Print the tree</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printTree</span><span class="hljs-params">(Node currPtr, String indent, <span class="hljs-keyword">boolean</span> last)</span> </span>{
<span class="hljs-keyword">if</span> (currPtr != <span class="hljs-keyword">null</span>) {
System.out.print(indent);
<span class="hljs-keyword">if</span> (last) {
System.out.print(<span class="hljs-string">"R----"</span>);
indent += <span class="hljs-string">" "</span>;
} <span class="hljs-keyword">else</span> {
System.out.print(<span class="hljs-string">"L----"</span>);
indent += <span class="hljs-string">"| "</span>;
}
System.out.println(currPtr.item);
printTree(currPtr.left, indent, <span class="hljs-keyword">false</span>);
printTree(currPtr.right, indent, <span class="hljs-keyword">true</span>);
}
}
<span class="hljs-comment">// Driver code</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
AVLTree tree = <span class="hljs-keyword">new</span> AVLTree();
tree.root = tree.insertNode(tree.root, <span class="hljs-number">33</span>);
tree.root = tree.insertNode(tree.root, <span class="hljs-number">13</span>);
tree.root = tree.insertNode(tree.root, <span class="hljs-number">53</span>);
tree.root = tree.insertNode(tree.root, <span class="hljs-number">9</span>);
tree.root = tree.insertNode(tree.root, <span class="hljs-number">21</span>);
tree.root = tree.insertNode(tree.root, <span class="hljs-number">61</span>);
tree.root = tree.insertNode(tree.root, <span class="hljs-number">8</span>);
tree.root = tree.insertNode(tree.root, <span class="hljs-number">11</span>);
tree.printTree(tree.root, <span class="hljs-string">""</span>, <span class="hljs-keyword">true</span>);
tree.root = tree.deleteNode(tree.root, <span class="hljs-number">13</span>);
System.out.println(<span class="hljs-string">"After Deletion: "</span>);
tree.printTree(tree.root, <span class="hljs-string">""</span>, <span class="hljs-keyword">true</span>);
}
}</code></pre></div>
</div>
<div class="code-editor__area" id="c-code">
<div class="pre-code-wrapper"><div title="Click to copy" class="copy-code-button"></div><pre class="exec" style="max-height: 600px;"><code class="c hljs cpp"><span class="hljs-comment">// AVL tree implementation in C</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string"><stdio.h></span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string"><stdlib.h></span></span>
<span class="hljs-comment">// Create Node</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> {</span>
<span class="hljs-keyword">int</span> key;
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">left</span>;</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">right</span>;</span>
<span class="hljs-keyword">int</span> height;
};
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">max</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span></span>;
<span class="hljs-comment">// Calculate height</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">height</span><span class="hljs-params">(struct Node *N)</span> </span>{
<span class="hljs-keyword">if</span> (N == <span class="hljs-literal">NULL</span>)
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
<span class="hljs-keyword">return</span> N->height;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">max</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
<span class="hljs-keyword">return</span> (a > b) ? a : b;
}
<span class="hljs-comment">// Create a node</span>
<span class="hljs-function">struct Node *<span class="hljs-title">newNode</span><span class="hljs-params">(<span class="hljs-keyword">int</span> key)</span> </span>{
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">node</span> = (<span class="hljs-title">struct</span> <span class="hljs-title">Node</span> *)
<span class="hljs-title">malloc</span>(<span class="hljs-title">sizeof</span>(<span class="hljs-title">struct</span> <span class="hljs-title">Node</span>));</span>
node->key = key;
node->left = <span class="hljs-literal">NULL</span>;
node->right = <span class="hljs-literal">NULL</span>;
node->height = <span class="hljs-number">1</span>;
<span class="hljs-keyword">return</span> (node);
}
<span class="hljs-comment">// Right rotate</span>
<span class="hljs-function">struct Node *<span class="hljs-title">rightRotate</span><span class="hljs-params">(struct Node *y)</span> </span>{
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">x</span> = <span class="hljs-title">y</span>-><span class="hljs-title">left</span>;</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">T2</span> = <span class="hljs-title">x</span>-><span class="hljs-title">right</span>;</span>
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + <span class="hljs-number">1</span>;
x->height = max(height(x->left), height(x->right)) + <span class="hljs-number">1</span>;
<span class="hljs-keyword">return</span> x;
}
<span class="hljs-comment">// Left rotate</span>
<span class="hljs-function">struct Node *<span class="hljs-title">leftRotate</span><span class="hljs-params">(struct Node *x)</span> </span>{
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">y</span> = <span class="hljs-title">x</span>-><span class="hljs-title">right</span>;</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">T2</span> = <span class="hljs-title">y</span>-><span class="hljs-title">left</span>;</span>
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + <span class="hljs-number">1</span>;
y->height = max(height(y->left), height(y->right)) + <span class="hljs-number">1</span>;
<span class="hljs-keyword">return</span> y;
}
<span class="hljs-comment">// Get the balance factor</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getBalance</span><span class="hljs-params">(struct Node *N)</span> </span>{
<span class="hljs-keyword">if</span> (N == <span class="hljs-literal">NULL</span>)
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
<span class="hljs-keyword">return</span> height(N->left) - height(N->right);
}
<span class="hljs-comment">// Insert node</span>
<span class="hljs-function">struct Node *<span class="hljs-title">insertNode</span><span class="hljs-params">(struct Node *node, <span class="hljs-keyword">int</span> key)</span> </span>{
<span class="hljs-comment">// Find the correct position to insertNode the node and insertNode it</span>
<span class="hljs-keyword">if</span> (node == <span class="hljs-literal">NULL</span>)
<span class="hljs-keyword">return</span> (newNode(key));
<span class="hljs-keyword">if</span> (key < node->key)
node->left = insertNode(node->left, key);
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key > node->key)
node->right = insertNode(node->right, key);
<span class="hljs-keyword">else</span>
<span class="hljs-keyword">return</span> node;
<span class="hljs-comment">// Update the balance factor of each node and</span>
<span class="hljs-comment">// Balance the tree</span>
node->height = <span class="hljs-number">1</span> + max(height(node->left),
height(node->right));
<span class="hljs-keyword">int</span> balance = getBalance(node);
<span class="hljs-keyword">if</span> (balance > <span class="hljs-number">1</span> && key < node->left->key)
<span class="hljs-keyword">return</span> rightRotate(node);
<span class="hljs-keyword">if</span> (balance < <span class="hljs-number">-1</span> && key > node->right->key)
<span class="hljs-keyword">return</span> leftRotate(node);
<span class="hljs-keyword">if</span> (balance > <span class="hljs-number">1</span> && key > node->left->key) {
node->left = leftRotate(node->left);
<span class="hljs-keyword">return</span> rightRotate(node);
}
<span class="hljs-keyword">if</span> (balance < <span class="hljs-number">-1</span> && key < node->right->key) {
node->right = rightRotate(node->right);
<span class="hljs-keyword">return</span> leftRotate(node);
}
<span class="hljs-keyword">return</span> node;
}
<span class="hljs-function">struct Node *<span class="hljs-title">minValueNode</span><span class="hljs-params">(struct Node *node)</span> </span>{
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">current</span> = <span class="hljs-title">node</span>;</span>
<span class="hljs-keyword">while</span> (current->left != <span class="hljs-literal">NULL</span>)
current = current->left;
<span class="hljs-keyword">return</span> current;
}
<span class="hljs-comment">// Delete a nodes</span>
<span class="hljs-function">struct Node *<span class="hljs-title">deleteNode</span><span class="hljs-params">(struct Node *root, <span class="hljs-keyword">int</span> key)</span> </span>{
<span class="hljs-comment">// Find the node and delete it</span>
<span class="hljs-keyword">if</span> (root == <span class="hljs-literal">NULL</span>)
<span class="hljs-keyword">return</span> root;
<span class="hljs-keyword">if</span> (key < root->key)
root->left = deleteNode(root->left, key);
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key > root->key)
root->right = deleteNode(root->right, key);
<span class="hljs-keyword">else</span> {
<span class="hljs-keyword">if</span> ((root->left == <span class="hljs-literal">NULL</span>) || (root->right == <span class="hljs-literal">NULL</span>)) {
struct Node *temp = root->left ? root->left : root->right;
<span class="hljs-keyword">if</span> (temp == <span class="hljs-literal">NULL</span>) {
temp = root;
root = <span class="hljs-literal">NULL</span>;
} <span class="hljs-keyword">else</span>
*root = *temp;
<span class="hljs-built_in">free</span>(temp);
} <span class="hljs-keyword">else</span> {
struct Node *temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
}
<span class="hljs-keyword">if</span> (root == <span class="hljs-literal">NULL</span>)
<span class="hljs-keyword">return</span> root;
<span class="hljs-comment">// Update the balance factor of each node and</span>
<span class="hljs-comment">// balance the tree</span>
root->height = <span class="hljs-number">1</span> + max(height(root->left),
height(root->right));
<span class="hljs-keyword">int</span> balance = getBalance(root);
<span class="hljs-keyword">if</span> (balance > <span class="hljs-number">1</span> && getBalance(root->left) >= <span class="hljs-number">0</span>)
<span class="hljs-keyword">return</span> rightRotate(root);
<span class="hljs-keyword">if</span> (balance > <span class="hljs-number">1</span> && getBalance(root->left) < <span class="hljs-number">0</span>) {
root->left = leftRotate(root->left);
<span class="hljs-keyword">return</span> rightRotate(root);
}
<span class="hljs-keyword">if</span> (balance < <span class="hljs-number">-1</span> && getBalance(root->right) <= <span class="hljs-number">0</span>)
<span class="hljs-keyword">return</span> leftRotate(root);
<span class="hljs-keyword">if</span> (balance < <span class="hljs-number">-1</span> && getBalance(root->right) > <span class="hljs-number">0</span>) {
root->right = rightRotate(root->right);
<span class="hljs-keyword">return</span> leftRotate(root);
}
<span class="hljs-keyword">return</span> root;
}
<span class="hljs-comment">// Print the tree</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printPreOrder</span><span class="hljs-params">(struct Node *root)</span> </span>{
<span class="hljs-keyword">if</span> (root != <span class="hljs-literal">NULL</span>) {
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d "</span>, root->key);
printPreOrder(root->left);
printPreOrder(root->right);
}
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span> *<span class="hljs-title">root</span> = <span class="hljs-title">NULL</span>;</span>
root = insertNode(root, <span class="hljs-number">2</span>);
root = insertNode(root, <span class="hljs-number">1</span>);
root = insertNode(root, <span class="hljs-number">7</span>);
root = insertNode(root, <span class="hljs-number">4</span>);
root = insertNode(root, <span class="hljs-number">5</span>);
root = insertNode(root, <span class="hljs-number">3</span>);
root = insertNode(root, <span class="hljs-number">8</span>);
printPreOrder(root);
root = deleteNode(root, <span class="hljs-number">3</span>);
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nAfter deletion: "</span>);
printPreOrder(root);
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre></div>
</div>
<div class="code-editor__area" id="cpp-code">
<div class="pre-code-wrapper"><div title="Click to copy" class="copy-code-button"></div><pre class="exec" style="max-height: 600px;"><code class="cpp hljs"><span class="hljs-comment">// AVL tree implementation in C++</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string"><iostream></span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span> {</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-keyword">int</span> key;
Node *left;
Node *right;
<span class="hljs-keyword">int</span> height;
};
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">max</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span></span>;
<span class="hljs-comment">// Calculate height</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">height</span><span class="hljs-params">(Node *N)</span> </span>{
<span class="hljs-keyword">if</span> (N == <span class="hljs-literal">NULL</span>)
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
<span class="hljs-keyword">return</span> N->height;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">max</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
<span class="hljs-keyword">return</span> (a > b) ? a : b;
}
<span class="hljs-comment">// New node creation</span>
<span class="hljs-function">Node *<span class="hljs-title">newNode</span><span class="hljs-params">(<span class="hljs-keyword">int</span> key)</span> </span>{
Node *node = <span class="hljs-keyword">new</span> Node();
node->key = key;
node->left = <span class="hljs-literal">NULL</span>;
node->right = <span class="hljs-literal">NULL</span>;
node->height = <span class="hljs-number">1</span>;
<span class="hljs-keyword">return</span> (node);
}
<span class="hljs-comment">// Rotate right</span>
<span class="hljs-function">Node *<span class="hljs-title">rightRotate</span><span class="hljs-params">(Node *y)</span> </span>{
Node *x = y->left;
Node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left),
height(y->right)) +
<span class="hljs-number">1</span>;
x->height = max(height(x->left),
height(x->right)) +
<span class="hljs-number">1</span>;
<span class="hljs-keyword">return</span> x;
}
<span class="hljs-comment">// Rotate left</span>
<span class="hljs-function">Node *<span class="hljs-title">leftRotate</span><span class="hljs-params">(Node *x)</span> </span>{
Node *y = x->right;
Node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left),
height(x->right)) +
<span class="hljs-number">1</span>;
y->height = max(height(y->left),
height(y->right)) +
<span class="hljs-number">1</span>;
<span class="hljs-keyword">return</span> y;
}
<span class="hljs-comment">// Get the balance factor of each node</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getBalanceFactor</span><span class="hljs-params">(Node *N)</span> </span>{
<span class="hljs-keyword">if</span> (N == <span class="hljs-literal">NULL</span>)
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
<span class="hljs-keyword">return</span> height(N->left) -
height(N->right);
}
<span class="hljs-comment">// Insert a node</span>
<span class="hljs-function">Node *<span class="hljs-title">insertNode</span><span class="hljs-params">(Node *node, <span class="hljs-keyword">int</span> key)</span> </span>{
<span class="hljs-comment">// Find the correct postion and insert the node</span>
<span class="hljs-keyword">if</span> (node == <span class="hljs-literal">NULL</span>)
<span class="hljs-keyword">return</span> (newNode(key));
<span class="hljs-keyword">if</span> (key < node->key)
node->left = insertNode(node->left, key);
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key > node->key)
node->right = insertNode(node->right, key);
<span class="hljs-keyword">else</span>
<span class="hljs-keyword">return</span> node;
<span class="hljs-comment">// Update the balance factor of each node and</span>
<span class="hljs-comment">// balance the tree</span>
node->height = <span class="hljs-number">1</span> + max(height(node->left),
height(node->right));
<span class="hljs-keyword">int</span> balanceFactor = getBalanceFactor(node);
<span class="hljs-keyword">if</span> (balanceFactor > <span class="hljs-number">1</span>) {
<span class="hljs-keyword">if</span> (key < node->left->key) {
<span class="hljs-keyword">return</span> rightRotate(node);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key > node->left->key) {
node->left = leftRotate(node->left);
<span class="hljs-keyword">return</span> rightRotate(node);
}
}
<span class="hljs-keyword">if</span> (balanceFactor < <span class="hljs-number">-1</span>) {
<span class="hljs-keyword">if</span> (key > node->right->key) {
<span class="hljs-keyword">return</span> leftRotate(node);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key < node->right->key) {
node->right = rightRotate(node->right);
<span class="hljs-keyword">return</span> leftRotate(node);
}
}
<span class="hljs-keyword">return</span> node;
}
<span class="hljs-comment">// Node with minimum value</span>
<span class="hljs-function">Node *<span class="hljs-title">nodeWithMimumValue</span><span class="hljs-params">(Node *node)</span> </span>{
Node *current = node;
<span class="hljs-keyword">while</span> (current->left != <span class="hljs-literal">NULL</span>)
current = current->left;
<span class="hljs-keyword">return</span> current;
}
<span class="hljs-comment">// Delete a node</span>
<span class="hljs-function">Node *<span class="hljs-title">deleteNode</span><span class="hljs-params">(Node *root, <span class="hljs-keyword">int</span> key)</span> </span>{