From 454ba8b6b52d8ffb3ea3222ddd3460db9f8716d9 Mon Sep 17 00:00:00 2001 From: ShivamDubey7 Date: Sat, 17 Oct 2020 11:39:23 +0530 Subject: [PATCH 01/20] Edited README --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4c46033c..165104f6 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,8 @@ -# Competitive-Programming-Algos -C++ implementation of algorithms learned and used while competitive programming +# Competitive Programming Runbook +During the years I spent playing around with competetive programming, here's an archive I prepared for the most useful reusable content I have been through. +I'm in the phase of collecting all my codes, making them generic enough to be understood/reused, and put it here. +Feel free to contribute, but make sure to maintain the quality - + From 806e8d52c3364202943e0988588763ef94172923 Mon Sep 17 00:00:00 2001 From: ShivamDubey7 Date: Sat, 17 Oct 2020 11:39:30 +0530 Subject: [PATCH 02/20] Renamed --- Convex Hull OPTIMISATION/main.cpp | 70 ------------------------------- 1 file changed, 70 deletions(-) delete mode 100644 Convex Hull OPTIMISATION/main.cpp diff --git a/Convex Hull OPTIMISATION/main.cpp b/Convex Hull OPTIMISATION/main.cpp deleted file mode 100644 index e354157c..00000000 --- a/Convex Hull OPTIMISATION/main.cpp +++ /dev/null @@ -1,70 +0,0 @@ -//it isn't too tough :) -#include -#define ll long long int -#define loop(i,a,b) for(int (i)=(a);(i)<(b);(i)++) -#define rep(i,n) for(int (i)=0;(i) ii; -const ll Lim=5*1e3+5; -vectorarr(Lim),lines; -ll n,k,dp[Lim][Lim],cumW[Lim],cumCost[Lim],h[Lim]; -bool irrelevant(ii l1,ii l2,ii l3){ - return (l1.S-l3.S)*(l2.F-l1.F) < (l1.S-l2.S)*(l3.F-l1.F); -} -void pre(){ - loop(i,1,n+1){ - cumW[i]=cumW[i-1]+arr[i].S; - cumCost[i] = cumCost[i-1] + arr[i].S*(arr[i].F-arr[1].F); - h[i]=arr[i].F-arr[1].F; - } -} -ll eval(ll a,ll ind){ - ll m = lines[ind].F; - ll c = lines[ind].S; - return cumW[a]*m+ c; -} -ll cal(ll n,ll kMax){ - loop(i,1,n+1) - dp[1][i]=cumCost[i]; - loop(k,2,kMax+1){ - ll i=0; - lines.clear(); - loop(a,k,n+1){ - if(sz(lines)<2){ - lines.pb(ii(-h[a],cumW[a-1]*h[a] - cumCost[a-1]+dp[k-1][a-1])); - } - else{ - ii l3 = ii(-h[a],cumW[a-1]*h[a] - cumCost[a-1]+dp[k-1][a-1]); - while(ieval(a,i+1)) - i++; - dp[k][a] = eval(a,i) + cumCost[a]; - } - } - return dp[kMax][n]; -} -void solve(){ - cin>>n>>k; - rep(i,n) - cin>>arr[i+1].F>>arr[i+1].S; - pre(); - ll ans = cal(n,k); - cout< Date: Sat, 17 Oct 2020 11:40:10 +0530 Subject: [PATCH 03/20] Renamed parent folder --- ConvexHullOptimisation/main.cpp | 70 +++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 ConvexHullOptimisation/main.cpp diff --git a/ConvexHullOptimisation/main.cpp b/ConvexHullOptimisation/main.cpp new file mode 100644 index 00000000..e354157c --- /dev/null +++ b/ConvexHullOptimisation/main.cpp @@ -0,0 +1,70 @@ +//it isn't too tough :) +#include +#define ll long long int +#define loop(i,a,b) for(int (i)=(a);(i)<(b);(i)++) +#define rep(i,n) for(int (i)=0;(i) ii; +const ll Lim=5*1e3+5; +vectorarr(Lim),lines; +ll n,k,dp[Lim][Lim],cumW[Lim],cumCost[Lim],h[Lim]; +bool irrelevant(ii l1,ii l2,ii l3){ + return (l1.S-l3.S)*(l2.F-l1.F) < (l1.S-l2.S)*(l3.F-l1.F); +} +void pre(){ + loop(i,1,n+1){ + cumW[i]=cumW[i-1]+arr[i].S; + cumCost[i] = cumCost[i-1] + arr[i].S*(arr[i].F-arr[1].F); + h[i]=arr[i].F-arr[1].F; + } +} +ll eval(ll a,ll ind){ + ll m = lines[ind].F; + ll c = lines[ind].S; + return cumW[a]*m+ c; +} +ll cal(ll n,ll kMax){ + loop(i,1,n+1) + dp[1][i]=cumCost[i]; + loop(k,2,kMax+1){ + ll i=0; + lines.clear(); + loop(a,k,n+1){ + if(sz(lines)<2){ + lines.pb(ii(-h[a],cumW[a-1]*h[a] - cumCost[a-1]+dp[k-1][a-1])); + } + else{ + ii l3 = ii(-h[a],cumW[a-1]*h[a] - cumCost[a-1]+dp[k-1][a-1]); + while(ieval(a,i+1)) + i++; + dp[k][a] = eval(a,i) + cumCost[a]; + } + } + return dp[kMax][n]; +} +void solve(){ + cin>>n>>k; + rep(i,n) + cin>>arr[i+1].F>>arr[i+1].S; + pre(); + ll ans = cal(n,k); + cout< Date: Sat, 17 Oct 2020 13:36:58 +0530 Subject: [PATCH 04/20] Added Kmp --- StringSearching/Kmp.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 StringSearching/Kmp.cpp diff --git a/StringSearching/Kmp.cpp b/StringSearching/Kmp.cpp new file mode 100644 index 00000000..ae975b72 --- /dev/null +++ b/StringSearching/Kmp.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; +void kmpPreProcess(string pattern, vector&lps){ + int i = 0,j=-1; + lps[0] = -1; + while(i=0 && pattern[i]!=pattern[j])j = lps[j]; + i++,j++; + lps[i]=j; + } +} +vector kmpSearch(string text, string pattern){ + vector ans; + vector lps(pattern.size()+1); + kmpPreProcess(pattern, lps); + int i = 0, j=-1; + while(i=0 && pattern[j]!=text[i])j=lps[j]; + i++;j++; + if(j==pattern.size()){ + ans.push_back(i-pattern.size()); + j = lps[j]; + } + } + return ans; +} +int main(){ + + string text = "Hey there! this is a text string, within which we wanna search a pattern. \ + Note that pattern repeats itself, so search for pattern if you wanna see can this report multiple occurrences of pattern."; + string pattern = "pattern"; + vector indices = kmpSearch(text,pattern); + for(auto i:indices){ + cout< Date: Sat, 17 Oct 2020 14:25:56 +0530 Subject: [PATCH 05/20] Added Linear String Search --- StringSearching/LinearSearch.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 StringSearching/LinearSearch.cpp diff --git a/StringSearching/LinearSearch.cpp b/StringSearching/LinearSearch.cpp new file mode 100644 index 00000000..5646176e --- /dev/null +++ b/StringSearching/LinearSearch.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; +vector linearSearch(string text, string pattern){ + vectorans; + for(int i=0;i indices = linearSearch(text,pattern); + for(auto i:indices){ + cout< Date: Sat, 17 Oct 2020 14:34:11 +0530 Subject: [PATCH 06/20] Added Fast exponentiation --- Maths/FastExponentiation.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Maths/FastExponentiation.cpp diff --git a/Maths/FastExponentiation.cpp b/Maths/FastExponentiation.cpp new file mode 100644 index 00000000..8bf0b1e3 --- /dev/null +++ b/Maths/FastExponentiation.cpp @@ -0,0 +1,18 @@ +#include +#define ll long long +using namespace std; +ll fastExpo(ll base, ll power){ + if(power==0) + return 1; + ll temp = fastExpo(base,power/2); + if(power&1){ + return temp*temp * base; + } + return temp*temp; +} +int main(){ + ll base = 5; + ll power = 3; + cout< Date: Sat, 17 Oct 2020 14:44:39 +0530 Subject: [PATCH 07/20] Adding Fast Exponentiation: both recursive and iterative method --- Maths/EulerGCD.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Maths/EulerGCD.cpp diff --git a/Maths/EulerGCD.cpp b/Maths/EulerGCD.cpp new file mode 100644 index 00000000..a2921575 --- /dev/null +++ b/Maths/EulerGCD.cpp @@ -0,0 +1,18 @@ +#include +using namespace std; +int iterativeGcd(int a,int b){ + while(a!=0){ + int rem = b%a; + b = a; + a = rem; + } + return b; +} +int recursiveGcd(int a, int b){ + if(a==0)return b; + return recursiveGcd(b%a,a); +} +int main(){ + int a = 6,b=4; + cout< Date: Sat, 17 Oct 2020 15:19:26 +0530 Subject: [PATCH 08/20] Added efficient MergeSort --- Sorting/MergeSort.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Sorting/MergeSort.cpp diff --git a/Sorting/MergeSort.cpp b/Sorting/MergeSort.cpp new file mode 100644 index 00000000..188a36ad --- /dev/null +++ b/Sorting/MergeSort.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; +void merge(vector&v, int startIndex, int mid, int endIndex){ + vectortemp; + int i1 = startIndex; + int i2 = mid+1; + while(i1<=mid && i2<=endIndex){ + if(v[i1]<=v[i2]) + temp.push_back(v[i1]),i1++; + else + temp.push_back(v[i2]),i2++; + } + while(i1<=mid)temp.push_back(v[i1]),i1++; + while(i2<=endIndex)temp.push_back(v[i2]),i2++; + for(int i=0;i&v, int startIndex, int endIndex){ + if(startIndextemp = {1,3,2,12,444,5}; + mergeSort(temp,0, temp.size()-1); + for(int v:temp){ + cout< Date: Sat, 17 Oct 2020 16:06:04 +0530 Subject: [PATCH 09/20] Added LinearSort --- Sorting/LinearSort.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Sorting/LinearSort.cpp diff --git a/Sorting/LinearSort.cpp b/Sorting/LinearSort.cpp new file mode 100644 index 00000000..78e61d92 --- /dev/null +++ b/Sorting/LinearSort.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; +void linearSort(vector&v){ + for(int i=0;itemp = {1,3,2,12,444,5}; + linearSort(temp); + for(int v:temp){ + cout< Date: Sat, 17 Oct 2020 17:47:48 +0530 Subject: [PATCH 10/20] Added HeapSort --- Sorting/HeapSort.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Sorting/HeapSort.cpp diff --git a/Sorting/HeapSort.cpp b/Sorting/HeapSort.cpp new file mode 100644 index 00000000..2d1d46fe --- /dev/null +++ b/Sorting/HeapSort.cpp @@ -0,0 +1,40 @@ +#include +#define sz(v) ((int)v.size()) +using namespace std; +void heapify(vector&v, int SIZE, int ind){ + int left_child = (ind<<1)+1; + int right_child = left_child+1; + int to_swap; + if(left_child v[ind]) + to_swap = left_child; + else + to_swap = ind; + if(right_child v[to_swap]) + to_swap = right_child; + if(to_swap !=ind){ + int temp = v[to_swap]; + v[to_swap] = v[ind]; + v[ind] = temp; + heapify(v,SIZE,to_swap); + } +} +void heapSort(vector&v){ + vectorheap(sz(v)); + for(int i=(sz(v)-2)/2;i>=0;i--){ + heapify(v,sz(v),i); + } + for(int i=sz(v)-1;i>0;i--){ + int temp = v[0]; + v[0] = v[i]; + v[i] = temp; + + heapify(v,i,0); + } +} +int main(){ + vectortemp = {1,3,2,12,444,5}; + heapSort(temp); + for(int v:temp){ + cout< Date: Sat, 17 Oct 2020 18:19:38 +0530 Subject: [PATCH 11/20] Added BinarySeach --- Searching/BinarySearch.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Searching/BinarySearch.cpp diff --git a/Searching/BinarySearch.cpp b/Searching/BinarySearch.cpp new file mode 100644 index 00000000..c0820198 --- /dev/null +++ b/Searching/BinarySearch.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; +//Create a predicate to return T/F for an ind +bool predicate(vector&v, int ind, int search_token){ + return v[ind] >= search_token; +} +int binarySeach(vector&v, int search_token){ + int low = 0,high = v.size(),mid; + while(low v = {1,2,4,5,11,20,25}; + cout< Date: Sun, 18 Oct 2020 08:24:30 +0530 Subject: [PATCH 12/20] Create bubblesort_java --- bubblesort_java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 bubblesort_java diff --git a/bubblesort_java b/bubblesort_java new file mode 100644 index 00000000..436662e3 --- /dev/null +++ b/bubblesort_java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} From 392deed9259907d30ba463703d2fc03ca21fcd9a Mon Sep 17 00:00:00 2001 From: huntingcodes <73046973+huntingcodes@users.noreply.github.com> Date: Sun, 18 Oct 2020 08:33:42 +0530 Subject: [PATCH 13/20] Create mirror inverse_java --- mirror inverse_java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 mirror inverse_java diff --git a/mirror inverse_java b/mirror inverse_java new file mode 100644 index 00000000..0f7c3b8c --- /dev/null +++ b/mirror inverse_java @@ -0,0 +1,28 @@ +// Java implementation of the approach +public class GFG { + + // Function that returns true if + // the array is mirror-inverse + static boolean isMirrorInverse(int arr[]) + { + for (int i = 0; i < arr.length; i++) { + + // If condition fails for any element + if (arr[arr[i]] != i) + return false; + } + + // Given array is mirror-inverse + return true; + } + + // Driver code + public static void main(String[] args) + { + int arr[] = { 1, 2, 3, 0 }; + if (isMirrorInverse(arr)) + System.out.println("Yes"); + else + System.out.println("No"); + } +} From 990b851b6e2898db749ebe969a3e2ddd8fb7fd81 Mon Sep 17 00:00:00 2001 From: huntingcodes <73046973+huntingcodes@users.noreply.github.com> Date: Sun, 18 Oct 2020 08:40:44 +0530 Subject: [PATCH 14/20] Create ascii-char_cpp --- ascii-char_cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 ascii-char_cpp diff --git a/ascii-char_cpp b/ascii-char_cpp new file mode 100644 index 00000000..697d3356 --- /dev/null +++ b/ascii-char_cpp @@ -0,0 +1,10 @@ +// CPP program to print +// ASCII Value of Character +#include +using namespace std; +int main() +{ + char c = 'A'; + cout << "The ASCII value of " << c << " is " << int(c); + return 0; +} From 1769869dc6eecab374a5d21d405d8d2fd55abaa9 Mon Sep 17 00:00:00 2001 From: ShivamDubey7 Date: Sun, 18 Oct 2020 11:58:40 +0530 Subject: [PATCH 15/20] Added Recursive BinarySeach --- Searching/BinarySearch.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Searching/BinarySearch.cpp b/Searching/BinarySearch.cpp index c0820198..1593eecb 100644 --- a/Searching/BinarySearch.cpp +++ b/Searching/BinarySearch.cpp @@ -17,8 +17,20 @@ int binarySeach(vector&v, int search_token){ if(v[low]==search_token) return low; return -1; } +int recursiveBinarySearch(vector&v, int search_token, int begin, int end){ + if(begin==end){ + if(v[begin]==search_token) + return begin; + return -1; + } + int mid = (begin+end)/2; + if(predicate(v,mid,search_token)){ + return recursiveBinarySearch(v,search_token,begin,mid); + } + return recursiveBinarySearch(v,search_token,mid+1,end); +} int main(){ vector v = {1,2,4,5,11,20,25}; - cout< Date: Sun, 18 Oct 2020 12:11:54 +0530 Subject: [PATCH 16/20] Renamed --- Sorting/BubbleSort.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Sorting/BubbleSort.java diff --git a/Sorting/BubbleSort.java b/Sorting/BubbleSort.java new file mode 100644 index 00000000..6932c335 --- /dev/null +++ b/Sorting/BubbleSort.java @@ -0,0 +1,34 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} From d63881b4c3928ccae4bd40b462c5d81aadbadae4 Mon Sep 17 00:00:00 2001 From: ShivamDubey7 Date: Sun, 18 Oct 2020 12:13:36 +0530 Subject: [PATCH 17/20] Removed --- bubblesort_java | 35 ----------------------------------- 1 file changed, 35 deletions(-) delete mode 100644 bubblesort_java diff --git a/bubblesort_java b/bubblesort_java deleted file mode 100644 index 436662e3..00000000 --- a/bubblesort_java +++ /dev/null @@ -1,35 +0,0 @@ -public class BubbleSortExample { - static void bubbleSort(int[] arr) { - int n = arr.length; - int temp = 0; - for(int i=0; i < n; i++){ - for(int j=1; j < (n-i); j++){ - if(arr[j-1] > arr[j]){ - //swap elements - temp = arr[j-1]; - arr[j-1] = arr[j]; - arr[j] = temp; - } - - } - } - - } - public static void main(String[] args) { - int arr[] ={3,60,35,2,45,320,5}; - - System.out.println("Array Before Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - System.out.println(); - - bubbleSort(arr);//sorting array elements using bubble sort - - System.out.println("Array After Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - - } -} From f1a9b4f65cee909d8532529e981b1bcc9c17e086 Mon Sep 17 00:00:00 2001 From: ShivamDubey7 Date: Sun, 18 Oct 2020 12:31:03 +0530 Subject: [PATCH 18/20] Added Iterative exponentiation --- Maths/FastExponentiation.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Maths/FastExponentiation.cpp b/Maths/FastExponentiation.cpp index 8bf0b1e3..4041dd00 100644 --- a/Maths/FastExponentiation.cpp +++ b/Maths/FastExponentiation.cpp @@ -10,9 +10,21 @@ ll fastExpo(ll base, ll power){ } return temp*temp; } +ll fastExpoIterative(ll base, ll power){ + ll res = 1; + while(power >0){ + if(power&1){ + res*=base; + } + power/=2; + base*=base; + } + return res; + +} int main(){ ll base = 5; ll power = 3; - cout< Date: Sun, 18 Oct 2020 12:50:45 +0530 Subject: [PATCH 19/20] Added DFS --- Graph/DFS.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Graph/DFS.cpp diff --git a/Graph/DFS.cpp b/Graph/DFS.cpp new file mode 100644 index 00000000..d60ceaaf --- /dev/null +++ b/Graph/DFS.cpp @@ -0,0 +1,27 @@ +#include +#define pb push_back +using namespace std; +const int LIM = 50; +int vis[LIM]; +vector >AdjList(LIM); +void dfs(int u){ + cout<>n>>m; + for(int i=0;i>u>>v; + AdjList[u].pb(v); + AdjList[v].pb(u); + } + dfs(1); + +} \ No newline at end of file From 26d22377df260b89d0149049eea565c0e1c7a3a9 Mon Sep 17 00:00:00 2001 From: nirbhaykumar780890 <93337897+nirbhaykumar780890@users.noreply.github.com> Date: Thu, 28 Oct 2021 21:21:18 +0530 Subject: [PATCH 20/20] Create AVL.java --- AVL.java | 154 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 AVL.java diff --git a/AVL.java b/AVL.java new file mode 100644 index 00000000..b876efe0 --- /dev/null +++ b/AVL.java @@ -0,0 +1,154 @@ +// Java program for insertion in AVL Tree +class Node { + int key, height; + Node left, right; + + Node(int d) { + key = d; + height = 1; + } +} + +class AVLTree { + + Node root; + + // A utility function to get the height of the tree + int height(Node N) { + if (N == null) + return 0; + + return N.height; + } + + // A utility function to get maximum of two integers + int max(int a, int b) { + return (a > b) ? a : b; + } + + // A utility function to right rotate subtree rooted with y + // See the diagram given above. + Node rightRotate(Node y) { + Node x = y.left; + Node T2 = x.right; + + // Perform rotation + x.right = y; + y.left = T2; + + // Update heights + y.height = max(height(y.left), height(y.right)) + 1; + x.height = max(height(x.left), height(x.right)) + 1; + + // Return new root + return x; + } + + // A utility function to left rotate subtree rooted with x + // See the diagram given above. + Node leftRotate(Node x) { + Node y = x.right; + Node T2 = y.left; + + // Perform rotation + y.left = x; + x.right = T2; + + // Update heights + x.height = max(height(x.left), height(x.right)) + 1; + y.height = max(height(y.left), height(y.right)) + 1; + + // Return new root + return y; + } + + // Get Balance factor of node N + int getBalance(Node N) { + if (N == null) + return 0; + + return height(N.left) - height(N.right); + } + + Node insert(Node node, int key) { + + /* 1. Perform the normal BST insertion */ + if (node == null) + return (new Node(key)); + + if (key < node.key) + node.left = insert(node.left, key); + else if (key > node.key) + node.right = insert(node.right, key); + else // Duplicate keys not allowed + return node; + + /* 2. Update height of this ancestor node */ + node.height = 1 + max(height(node.left), + height(node.right)); + + /* 3. Get the balance factor of this ancestor + node to check whether this node became + unbalanced */ + int balance = getBalance(node); + + // If this node becomes unbalanced, then there + // are 4 cases Left Left Case + if (balance > 1 && key < node.left.key) + return rightRotate(node); + + // Right Right Case + if (balance < -1 && key > node.right.key) + return leftRotate(node); + + // Left Right Case + if (balance > 1 && key > node.left.key) { + node.left = leftRotate(node.left); + return rightRotate(node); + } + + // Right Left Case + if (balance < -1 && key < node.right.key) { + node.right = rightRotate(node.right); + return leftRotate(node); + } + + /* return the (unchanged) node pointer */ + return node; + } + + // A utility function to print preorder traversal + // of the tree. + // The function also prints height of every node + void preOrder(Node node) { + if (node != null) { + System.out.print(node.key + " "); + preOrder(node.left); + preOrder(node.right); + } + } + + public static void main(String[] args) { + AVLTree tree = new AVLTree(); + + /* Constructing tree given in the above figure */ + tree.root = tree.insert(tree.root, 10); + tree.root = tree.insert(tree.root, 20); + tree.root = tree.insert(tree.root, 30); + tree.root = tree.insert(tree.root, 40); + tree.root = tree.insert(tree.root, 50); + tree.root = tree.insert(tree.root, 25); + + /* The constructed AVL Tree would be + 30 + / \ + 20 40 + / \ \ + 10 25 50 + */ + System.out.println("Preorder traversal" + + " of constructed tree is : "); + tree.preOrder(tree.root); + } +} +// This code has been contributed by Mayank Jaiswal