text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Decimal equivalent of concatenation of absolute difference of floor and rounded | C ++ program for the above approach ; Function to find the decimal equivalent of the new binary array constructed from absolute decimal of floor and the round - off values ; Traverse the givenarray from the end ; Stores the absolute difference between floor and round - off each array element ; If bit / difference is 1 , then calculate the bit by proper power of 2 and add it to result ; Increment the value of power ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findDecimal ( float arr [ ] , int N ) { int bit , power = 0 , result = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { bit = abs ( floor ( arr [ i ] ) - round ( arr [ i ] ) ) ; if ( bit ) result += pow ( 2 , power ) ; power ++ ; } cout << result ; } int main ( ) { float arr [ ] = { 1.2 , 2.6 , 4.2 , 6.9 , 3.1 , 21.6 , 91.2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findDecimal ( arr , N ) ; return 0 ; } |
Calculate money placed in boxes after N days based on given conditions | C ++ program for the above approach ; Function to find the total money placed in boxes after N days ; Stores the total money ; Iterate for N days ; Adding the Week number ; Adding previous amount + 1 ; Return the total amount ; Driver code ; Input ; Function call to find total money placed | #include <iostream> NEW_LINE using namespace std ; int totalMoney ( int N ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { ans += i / 7 ; ans += ( i % 7 + 1 ) ; } return ans ; } int main ( ) { int N = 15 ; cout << totalMoney ( N ) ; } |
Calculate money placed in boxes after N days based on given conditions | C ++ Program to implement the above approach ; Function to find total money placed in the box ; Number of complete weeks ; Remaining days in the last week ; Driver Code ; Input ; Function call to find the total money placed | #include <bits/stdc++.h> NEW_LINE using namespace std ; int totalMoney ( int N ) { int CompWeeks = N / 7 ; int RemDays = N % 7 ; int X = 28 * CompWeeks + 7 * ( CompWeeks * ( CompWeeks - 1 ) / 2 ) ; int Y = RemDays * ( RemDays + 1 ) / 2 + CompWeeks * RemDays ; int cost = X + Y ; cout << cost << ' ' ; } int main ( ) { int N = 15 ; totalMoney ( N ) ; return 0 ; } |
Sum of absolute differences of indices of occurrences of each array element | Set 2 | C ++ program for the above approach ; Stores the count of occurrences and previous index of every element ; Constructor ; Function to calculate the sum of absolute differences of indices of occurrences of array element ; Stores the count of elements and their previous indices ; Initialize 2 arrays left [ ] and right [ ] of size N ; Traverse the given array ; If arr [ i ] is present in the Map ; Update left [ i ] to 0 and update the value of arr [ i ] in map ; Otherwise , get the value from the map and update left [ i ] ; Clear the map to calculate right [ ] array ; Traverse the array arr [ ] in reverse ; If arr [ i ] is present in theMap ; Update right [ i ] to 0 and update the value of arr [ i ] in the Map ; Otherwise get the value from the map and update right [ i ] ; Iterate in the range [ 0 , N - 1 ] and print the sum of left [ i ] and right [ i ] as the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct pairr { int count , prevIndex ; pairr ( int countt , int prevIndexx ) { count = countt ; prevIndex = prevIndexx ; } } ; void findSum ( int arr [ ] , int n ) { map < int , pairr * > mapp ; int left [ n ] ; int right [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( mapp . find ( arr [ i ] ) == mapp . end ( ) ) { left [ i ] = 0 ; mapp [ arr [ i ] ] = new pairr ( 1 , i ) ; } else { pairr * tmp = mapp [ arr [ i ] ] ; left [ i ] = ( tmp -> count ) * ( i - tmp -> prevIndex ) + left [ tmp -> prevIndex ] ; mapp [ arr [ i ] ] = new pairr ( tmp -> count + 1 , i ) ; } } mapp . clear ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( mapp . find ( arr [ i ] ) == mapp . end ( ) ) { right [ i ] = 0 ; mapp [ arr [ i ] ] = new pairr ( 1 , i ) ; } else { pairr * tmp = mapp [ arr [ i ] ] ; right [ i ] = ( tmp -> count ) * ( abs ( i - tmp -> prevIndex ) ) + right [ tmp -> prevIndex ] ; mapp [ arr [ i ] ] = new pairr ( tmp -> count + 1 , i ) ; } } for ( int i = 0 ; i < n ; i ++ ) cout << left [ i ] + right [ i ] << " β " ; } int main ( ) { int arr [ ] = { 1 , 3 , 1 , 1 , 2 } ; int N = 5 ; findSum ( arr , N ) ; } |
Convert a number to another by dividing by its factor or removing first occurrence of a digit from an array | C ++ program for the above approach ; Function to check if a digit x is present in the number N or not ; Convert N to string ; Traverse the string num ; Return first occurrence of the digit x ; Function to remove the character at a given index from the number ; Convert N to string ; Store the resultant string ; Traverse the string num ; If the number becomes empty after deletion , then return - 1 ; Return the number ; Function to check if A can be reduced to B by performing the operations any number of times ; Create a queue ; Push A into the queue ; Hashmap to check if the element is present in the Queue or not ; Set A as visited ; Iterate while the queue is not empty ; Store the front value of the queue and pop it from it ; If top is equal to B , then return true ; Traverse the array , D [ ] ; Divide top by D [ i ] if it is possible and push the result in q ; If D [ i ] is present at the top ; Remove the first occurrence of D [ i ] from the top and store the new number ; Push newElement into the queue q ; Return false if A can not be reduced to B ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isPresent ( int n , int x ) { string num = to_string ( n ) ; for ( int i = 0 ; i < num . size ( ) ; i ++ ) { if ( ( num [ i ] - '0' ) == x ) return i ; } return -1 ; } int removeDigit ( int n , int index ) { string num = to_string ( n ) ; string ans = " " ; for ( int i = 0 ; i < num . size ( ) ; i ++ ) { if ( i != index ) ans += num [ i ] ; } if ( ans == " " || ( ans . size ( ) == 1 && ans [ 0 ] == '0' ) ) return -1 ; int x = stoi ( ans ) ; return x ; } bool reduceNtoX ( int a , int b , int d [ ] , int n ) { queue < int > q ; q . push ( a ) ; unordered_map < int , bool > visited ; visited [ a ] = true ; while ( ! q . empty ( ) ) { int top = q . front ( ) ; q . pop ( ) ; if ( top < 0 ) continue ; if ( top == b ) return true ; for ( int i = 0 ; i < n ; i ++ ) { if ( d [ i ] != 0 && top % d [ i ] == 0 && ! visited [ top / d [ i ] ] ) { q . push ( top / d [ i ] ) ; visited [ top / d [ i ] ] = true ; } int index = isPresent ( top , d [ i ] ) ; if ( index != -1 ) { int newElement = removeDigit ( top , index ) ; if ( newElement != -1 && ( ! visited [ newElement ] ) ) { q . push ( newElement ) ; visited [ newElement ] = true ; } } } } return false ; } int main ( ) { int A = 5643 , B = 81 ; int D [ ] = { 3 , 8 , 1 } ; int N = sizeof ( D ) / sizeof ( D [ 0 ] ) ; if ( reduceNtoX ( A , B , D , N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Prime triplets consisting of values up to N having difference between two elements equal to the third | C ++ program for the above approach ; Stores 1 and 0 at indices which are prime and non - prime respectively ; Function to find all prime numbers from the range [ 0 , N ] ; Consider all numbers to prime initially ; Iterate over the range [ 2 , sqrt ( N ) ] ; If p is a prime ; Update all tultiples of p as false ; Function to find all prime triplets satisfying the given conditions ; Generate all primes up to N ; Stores the triplets ; Iterate over the range [ 3 , N ] ; Check for the condition ; Store the triplets ; Print all the stored triplets ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 100000 ] ; void SieveOfEratosthenes ( int n ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) { prime [ i ] = false ; } } } } void findTriplets ( int N ) { SieveOfEratosthenes ( N ) ; vector < vector < int > > V ; for ( int i = 3 ; i <= N ; i ++ ) { if ( 2 + i <= N && prime [ i ] && prime [ 2 + i ] ) { V . push_back ( { 2 , i , i + 2 } ) ; } } for ( int i = 0 ; i < V . size ( ) ; i ++ ) { cout << V [ i ] [ 0 ] << " β " << V [ i ] [ 1 ] << " β " << V [ i ] [ 2 ] << " STRNEWLINE " ; } } int main ( ) { int N = 8 ; findTriplets ( N ) ; return 0 ; } |
2 | C ++ implementation to find if the given expression is satisfiable using the Kosaraju 's Algorithm ; data structures used to implement Kosaraju 's Algorithm. Please refer http:www.geeksforgeeks.org/strongly-connected-components/ ; this array will store the SCC that the particular node belongs to ; counter maintains the number of the SCC ; adds edges to form the original graph ; add edges to form the inverse graph ; for STEP 1 of Kosaraju 's Algorithm ; for STEP 2 of Kosaraju 's Algorithm ; function to check 2 - Satisfiability ; adding edges to the graph ; variable x is mapped to x variable - x is mapped to n + x = n - ( - x ) for a [ i ] or b [ i ] , addEdges - a [ i ] -> b [ i ] AND - b [ i ] -> a [ i ] ; STEP 1 of Kosaraju 's Algorithm which traverses the original graph ; STEP 2 pf Kosaraju 's Algorithm which traverses the inverse graph. After this, array scc[] stores the corresponding value ; for any 2 vairable x and - x lie in same SCC ; no such variables x and - x exist which lie in same SCC ; Driver function to test above functions ; n is the number of variables 2 n is the total number of nodes m is the number of clauses ; each clause is of the form a or b for m clauses , we have a [ m ] , b [ m ] representing a [ i ] or b [ i ] Note : 1 <= x <= N for an uncomplemented variable x - N <= x <= - 1 for a complemented variable x - x is the complement of a variable x The CNF being handled is : ' + ' implies ' OR ' and ' * ' implies ' AND ' ( x1 + x2 ) * ( x2 + x3 ) * ( x1 + x2 ) * ( x3 + x4 ) * ( x3 + x5 ) * ( x4 + x5 ) * ( x3 + x4 ) ; We have considered the same example for which Implication Graph was made | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100000 ; vector < int > adj [ MAX ] ; vector < int > adjInv [ MAX ] ; bool visited [ MAX ] ; bool visitedInv [ MAX ] ; stack < int > s ; int scc [ MAX ] ; int counter = 1 ; void addEdges ( int a , int b ) { adj [ a ] . push_back ( b ) ; } void addEdgesInverse ( int a , int b ) { adjInv [ b ] . push_back ( a ) ; } void dfsFirst ( int u ) { if ( visited [ u ] ) return ; visited [ u ] = 1 ; for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) dfsFirst ( adj [ u ] [ i ] ) ; s . push ( u ) ; } void dfsSecond ( int u ) { if ( visitedInv [ u ] ) return ; visitedInv [ u ] = 1 ; for ( int i = 0 ; i < adjInv [ u ] . size ( ) ; i ++ ) dfsSecond ( adjInv [ u ] [ i ] ) ; scc [ u ] = counter ; } void is2Satisfiable ( int n , int m , int a [ ] , int b [ ] ) { for ( int i = 0 ; i < m ; i ++ ) { if ( a [ i ] > 0 && b [ i ] > 0 ) { addEdges ( a [ i ] + n , b [ i ] ) ; addEdgesInverse ( a [ i ] + n , b [ i ] ) ; addEdges ( b [ i ] + n , a [ i ] ) ; addEdgesInverse ( b [ i ] + n , a [ i ] ) ; } else if ( a [ i ] > 0 && b [ i ] < 0 ) { addEdges ( a [ i ] + n , n - b [ i ] ) ; addEdgesInverse ( a [ i ] + n , n - b [ i ] ) ; addEdges ( - b [ i ] , a [ i ] ) ; addEdgesInverse ( - b [ i ] , a [ i ] ) ; } else if ( a [ i ] < 0 && b [ i ] > 0 ) { addEdges ( - a [ i ] , b [ i ] ) ; addEdgesInverse ( - a [ i ] , b [ i ] ) ; addEdges ( b [ i ] + n , n - a [ i ] ) ; addEdgesInverse ( b [ i ] + n , n - a [ i ] ) ; } else { addEdges ( - a [ i ] , n - b [ i ] ) ; addEdgesInverse ( - a [ i ] , n - b [ i ] ) ; addEdges ( - b [ i ] , n - a [ i ] ) ; addEdgesInverse ( - b [ i ] , n - a [ i ] ) ; } } for ( int i = 1 ; i <= 2 * n ; i ++ ) if ( ! visited [ i ] ) dfsFirst ( i ) ; while ( ! s . empty ( ) ) { int n = s . top ( ) ; s . pop ( ) ; if ( ! visitedInv [ n ] ) { dfsSecond ( n ) ; counter ++ ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( scc [ i ] == scc [ i + n ] ) { cout << " The β given β expression β " " is β unsatisfiable . " << endl ; return ; } } cout << " The β given β expression β is β satisfiable . " << endl ; return ; } int main ( ) { int n = 5 , m = 7 ; int a [ ] = { 1 , -2 , -1 , 3 , -3 , -4 , -3 } ; int b [ ] = { 2 , 3 , -2 , 4 , 5 , -5 , 4 } ; is2Satisfiable ( n , m , a , b ) ; return 0 ; } |
Smallest number which is not coprime with any element of an array | C ++ program for the above approach ; Function check if a number is prime or not ; Corner cases ; Check if n is divisible by 2 or 3 ; Check for every 6 th number . The above checking allows to skip middle 5 numbers ; Function to store primes in an array ; Function to calculate GCD of two numbers ; Function to find the smallest number which is not coprime with any element of the array arr [ ] ; Function call to fill the prime numbers ; Stores the answer ; Generate all non - empty subsets of the primes [ ] array ; Stores product of the primes ; Checks if temp is coprime with the array or not ; Check if the product temp is not coprime with the whole array ; If the product is not co - prime with the array ; Print the answer ; Driver Code ; Given array ; Stores the size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE #define MAX 50 NEW_LINE bool isPrime ( ll n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( ll i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } void findPrime ( vector < ll > & primes ) { for ( ll i = 2 ; i <= MAX ; i ++ ) { if ( isPrime ( i ) ) primes . push_back ( i ) ; } } ll gcd ( ll a , ll b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } void findMinimumNumber ( ll arr [ ] , ll N ) { vector < ll > primes ; findPrime ( primes ) ; ll ans = INT_MAX ; ll n = primes . size ( ) ; for ( ll i = 1 ; i < ( 1 << n ) ; i ++ ) { ll temp = 1 ; for ( ll j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) { temp *= primes [ j ] ; } } bool check = true ; for ( ll k = 0 ; k < N ; k ++ ) { if ( gcd ( temp , arr [ k ] ) == 1 ) { check = false ; break ; } } if ( check ) ans = min ( ans , temp ) ; } cout << ans ; } int main ( ) { ll arr [ ] = { 3 , 4 , 6 , 7 , 8 , 9 , 10 } ; ll N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMinimumNumber ( arr , N ) ; return 0 ; } |
Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits | C ++ program for the above approach ; Function to check if a number N can be expressed as sum of its digits raised to the power of the count of digits ; Stores the number of digits ; Stores the resultant number ; Return true if both the numbers are same ; Function to precompute and store for all numbers whether they can be expressed ; Mark all the index which are plus perfect number ; If true , then update the value at this index ; Compute prefix sum of the array ; Function to count array elements that can be expressed as the sum of digits raised to the power of count of digits ; Precompute the results ; Traverse the queries ; Print the resultant count ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 100005 NEW_LINE int arr [ R ] ; bool canExpress ( int N ) { int temp = N ; int n = 0 ; while ( N != 0 ) { N /= 10 ; n ++ ; } N = temp ; int sum = 0 ; while ( N != 0 ) { sum += pow ( N % 10 , n ) ; N /= 10 ; } return ( sum == temp ) ; } void precompute ( ) { for ( int i = 1 ; i < R ; i ++ ) { if ( canExpress ( i ) ) { arr [ i ] = 1 ; } } for ( int i = 1 ; i < R ; i ++ ) { arr [ i ] += arr [ i - 1 ] ; } } void countNumbers ( int queries [ ] [ 2 ] , int N ) { precompute ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int L1 = queries [ i ] [ 0 ] ; int R1 = queries [ i ] [ 1 ] ; cout << ( arr [ R1 ] - arr [ L1 - 1 ] ) << ' β ' ; } } int main ( ) { int queries [ ] [ 2 ] = { { 1 , 400 } , { 1 , 9 } } ; int N = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; countNumbers ( queries , N ) ; return 0 ; } |
Queries to calculate sum of the path from root to a given node in given Binary Tree | C ++ program for the above approach ; Function to find the sum of the path from root to the current node ; Sum of nodes in the path ; Iterate until root is reached ; Update the node value ; Print the resultant sum ; Function to print the path sum for each query ; Traverse the queries ; Driver Code ; arraylist to store integers | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void sumOfNodeInAPath ( int node_value ) { int sum_of_node = 0 ; while ( node_value ) { sum_of_node += node_value ; node_value /= 2 ; } cout << sum_of_node ; return ; } void findSum ( vector < int > Q ) { for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { int node_value = Q [ i ] ; sumOfNodeInAPath ( node_value ) ; cout << " β " ; } } int main ( ) { vector < int > arr = { 1 , 5 , 20 , 100 } ; findSum ( arr ) ; return 0 ; } |
Minimum removals required to make frequency of all remaining array elements equal | C ++ program for the above approach ; Function to count the minimum removals required to make frequency of all array elements equal ; Stores frequency of all array elements ; Traverse the array ; Stores all the frequencies ; Traverse the map ; Sort the frequencies ; Count of frequencies ; Stores the final count ; Traverse the vector ; Count the number of removals for each frequency and update the minimum removals required ; Print the final count ; Driver Code ; Given array ; Size of the array ; Function call to print the minimum number of removals required | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDeletions ( int arr [ ] , int N ) { map < int , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] ] ++ ; } vector < int > v ; for ( auto z : freq ) { v . push_back ( z . second ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int size = v . size ( ) ; int ans = N - ( v [ 0 ] * size ) ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) { if ( v [ i ] != v [ i - 1 ] ) { int safe = v [ i ] * ( size - i ) ; ans = min ( ans , N - safe ) ; } } cout << ans ; } int main ( ) { int arr [ ] = { 2 , 4 , 3 , 2 , 5 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minDeletions ( arr , N ) ; } |
Check if a string is the typed name of the given name | CPP program to implement run length encoding ; Check if the character is vowel or not ; Returns true if ' typed ' is a typed name given str ; Traverse through all characters of str . ; If current characters do not match ; If not vowel , simply move ahead in both ; Count occurrences of current vowel in str ; Count occurrences of current vowel in typed . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { string vowel = " aeiou " ; for ( int i = 0 ; i < vowel . length ( ) ; ++ i ) if ( vowel [ i ] == c ) return true ; return false ; } bool printRLE ( string str , string typed ) { int n = str . length ( ) , m = typed . length ( ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] != typed [ j ] ) return false ; if ( isVowel ( str [ i ] ) == false ) { j ++ ; continue ; } int count1 = 1 ; while ( i < n - 1 && str [ i ] == str [ i + 1 ] ) { count1 ++ ; i ++ ; } int count2 = 1 ; while ( j < m - 1 && typed [ j ] == str [ i ] ) { count2 ++ ; j ++ ; } if ( count1 > count2 ) return false ; } return true ; } int main ( ) { string name = " alex " , typed = " aaalaeex " ; if ( printRLE ( name , typed ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Reverse alternate levels of a perfect binary tree | C ++ program to reverse alternate levels of a tree ; Base cases ; Swap subtrees if level is even ; Recur for left and right subtrees ( Note : left of root1 is passed and right of root2 in first call and opposite in second call . ; This function calls preorder ( ) for left and right children of root ; Inorder traversal ( used to print initial andmodified trees ) ; A utility function to create a new node ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { char key ; Node * left , * right ; } ; void preorder ( struct Node * root1 , struct Node * root2 , int lvl ) { if ( root1 == NULL root2 == NULL ) return ; if ( lvl % 2 == 0 ) swap ( root1 -> key , root2 -> key ) ; preorder ( root1 -> left , root2 -> right , lvl + 1 ) ; preorder ( root1 -> right , root2 -> left , lvl + 1 ) ; } void reverseAlternate ( struct Node * root ) { preorder ( root -> left , root -> right , 0 ) ; } void printInorder ( struct Node * root ) { if ( root == NULL ) return ; printInorder ( root -> left ) ; cout << root -> key << " β " ; printInorder ( root -> right ) ; } Node * newNode ( int key ) { Node * temp = new Node ; temp -> left = temp -> right = NULL ; temp -> key = key ; return temp ; } int main ( ) { struct Node * root = newNode ( ' a ' ) ; root -> left = newNode ( ' b ' ) ; root -> right = newNode ( ' c ' ) ; root -> left -> left = newNode ( ' d ' ) ; root -> left -> right = newNode ( ' e ' ) ; root -> right -> left = newNode ( ' f ' ) ; root -> right -> right = newNode ( ' g ' ) ; root -> left -> left -> left = newNode ( ' h ' ) ; root -> left -> left -> right = newNode ( ' i ' ) ; root -> left -> right -> left = newNode ( ' j ' ) ; root -> left -> right -> right = newNode ( ' k ' ) ; root -> right -> left -> left = newNode ( ' l ' ) ; root -> right -> left -> right = newNode ( ' m ' ) ; root -> right -> right -> left = newNode ( ' n ' ) ; root -> right -> right -> right = newNode ( ' o ' ) ; cout << " Inorder β Traversal β of β given β tree STRNEWLINE " ; printInorder ( root ) ; reverseAlternate ( root ) ; cout << " Inorder Traversal of modified tree " ; printInorder ( root ) ; return 0 ; } |
Deletion in a Binary Tree | C ++ program to delete element in binary tree ; A binary tree node has key , pointer to left child and a pointer to right child ; function to create a new node of tree and return pointer ; Inorder traversal of a binary tree ; function to delete the given deepest node ( d_node ) in binary tree ; Do level order traversal until last node ; function to delete element in binary tree ; Do level order traversal to find deepest node ( temp ) and node to be deleted ( key_node ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; struct Node * newNode ( int key ) { struct Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } ; void inorder ( struct Node * temp ) { if ( ! temp ) return ; inorder ( temp -> left ) ; cout << temp -> key << " β " ; inorder ( temp -> right ) ; } void deletDeepest ( struct Node * root , struct Node * d_node ) { queue < struct Node * > q ; q . push ( root ) ; struct Node * temp ; while ( ! q . empty ( ) ) { temp = q . front ( ) ; q . pop ( ) ; if ( temp == d_node ) { temp = NULL ; delete ( d_node ) ; return ; } if ( temp -> right ) { if ( temp -> right == d_node ) { temp -> right = NULL ; delete ( d_node ) ; return ; } else q . push ( temp -> right ) ; } if ( temp -> left ) { if ( temp -> left == d_node ) { temp -> left = NULL ; delete ( d_node ) ; return ; } else q . push ( temp -> left ) ; } } } Node * deletion ( struct Node * root , int key ) { if ( root == NULL ) return NULL ; if ( root -> left == NULL && root -> right == NULL ) { if ( root -> key == key ) return NULL ; else return root ; } queue < struct Node * > q ; q . push ( root ) ; struct Node * temp ; struct Node * key_node = NULL ; while ( ! q . empty ( ) ) { temp = q . front ( ) ; q . pop ( ) ; if ( temp -> key == key ) key_node = temp ; if ( temp -> left ) q . push ( temp -> left ) ; if ( temp -> right ) q . push ( temp -> right ) ; } if ( key_node != NULL ) { int x = temp -> key ; deletDeepest ( root , temp ) ; key_node -> key = x ; } return root ; } int main ( ) { struct Node * root = newNode ( 10 ) ; root -> left = newNode ( 11 ) ; root -> left -> left = newNode ( 7 ) ; root -> left -> right = newNode ( 12 ) ; root -> right = newNode ( 9 ) ; root -> right -> left = newNode ( 15 ) ; root -> right -> right = newNode ( 8 ) ; cout << " Inorder β traversal β before β deletion β : β " ; inorder ( root ) ; int key = 11 ; root = deletion ( root , key ) ; cout << endl ; cout << " Inorder β traversal β after β deletion β : β " ; inorder ( root ) ; return 0 ; } |
Number of sink nodes in a graph | C ++ program to count number if sink nodes ; Return the number of Sink NOdes . ; Array for marking the non - sink node . ; Marking the non - sink node . ; Counting the sink nodes . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSink ( int n , int m , int edgeFrom [ ] , int edgeTo [ ] ) { int mark [ n ] ; memset ( mark , 0 , sizeof mark ) ; for ( int i = 0 ; i < m ; i ++ ) mark [ edgeFrom [ i ] ] = 1 ; int count = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( ! mark [ i ] ) count ++ ; return count ; } int main ( ) { int n = 4 , m = 2 ; int edgeFrom [ ] = { 2 , 4 } ; int edgeTo [ ] = { 3 , 3 } ; cout << countSink ( n , m , edgeFrom , edgeTo ) << endl ; return 0 ; } |
Largest subset of Graph vertices with edges of 2 or more colors | C ++ program to find size of subset of graph vertex such that each vertex has more than 1 color edges ; Number of vertices ; function to calculate max subset size ; set for number of vertices ; loop for deletion of vertex from set ; if subset has only 1 vertex return 0 ; for each vertex iterate and keep removing a vertix while we find a vertex with all edges of same color . ; note down different color values for each vertex ; if only one color is found erase that vertex ( bad vertex ) ; If no vertex was removed in the above loop . ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 6 ; int subsetGraph ( int C [ ] [ N ] ) { set < int > vertices ; for ( int i = 0 ; i < N ; ++ i ) vertices . insert ( i ) ; while ( ! vertices . empty ( ) ) { if ( vertices . size ( ) == 1 ) return 1 ; bool someone_removed = false ; for ( int x : vertices ) { set < int > values ; for ( int y : vertices ) if ( y != x ) values . insert ( C [ x ] [ y ] ) ; if ( values . size ( ) == 1 ) { vertices . erase ( x ) ; someone_removed = true ; break ; } } if ( ! someone_removed ) break ; } return ( vertices . size ( ) ) ; } int main ( ) { int C [ ] [ N ] = { { 0 , 9 , 2 , 4 , 7 , 8 } , { 9 , 0 , 9 , 9 , 7 , 9 } , { 2 , 9 , 0 , 3 , 7 , 6 } , { 4 , 9 , 3 , 0 , 7 , 1 } , { 7 , 7 , 7 , 7 , 0 , 7 } , { 8 , 9 , 6 , 1 , 7 , 0 } } ; cout << subsetGraph ( C ) ; return 0 ; } |
Count number of edges in an undirected graph | C ++ program to count number of edge in undirected graph ; Adjacency list representation of graph ; add edge to graph ; Returns count of edge in undirected graph ; traverse all vertex ; add all edge that are linked to the current vertex ; The count of edge is always even because in undirected graph every edge is connected twice between two vertices ; driver program to check above function ; making above uhown graph | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Graph { int V ; list < int > * adj ; public : Graph ( int V ) { this -> V = V ; adj = new list < int > [ V ] ; } void addEdge ( int u , int v ) ; int countEdges ( ) ; } ; void Graph :: addEdge ( int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } int Graph :: countEdges ( ) { int sum = 0 ; for ( int i = 0 ; i < V ; i ++ ) sum += adj [ i ] . size ( ) ; return sum / 2 ; } int main ( ) { int V = 9 ; Graph g ( V ) ; g . addEdge ( 0 , 1 ) ; g . addEdge ( 0 , 7 ) ; g . addEdge ( 1 , 2 ) ; g . addEdge ( 1 , 7 ) ; g . addEdge ( 2 , 3 ) ; g . addEdge ( 2 , 8 ) ; g . addEdge ( 2 , 5 ) ; g . addEdge ( 3 , 4 ) ; g . addEdge ( 3 , 5 ) ; g . addEdge ( 4 , 5 ) ; g . addEdge ( 5 , 6 ) ; g . addEdge ( 6 , 7 ) ; g . addEdge ( 6 , 8 ) ; g . addEdge ( 7 , 8 ) ; cout << g . countEdges ( ) << endl ; return 0 ; } |
Two Clique Problem ( Check if Graph can be divided in two Cliques ) | C ++ program to find out whether a given graph can be converted to two Cliques or not . ; This function returns true if subgraph reachable from src is Bipartite or not . ; Create a queue ( FIFO ) of vertex numbers and enqueue source vertex for BFS traversal ; Run while there are vertices in queue ( Similar to BFS ) ; Dequeue a vertex from queue ; Find all non - colored adjacent vertices ; An edge from u to v exists and destination v is not colored ; Assign alternate color to this adjacent v of u ; An edge from u to v exists and destination v is colored with same color as u ; If we reach here , then all adjacent vertices can be colored with alternate color ; Returns true if a Graph G [ ] [ ] is Bipartite or not . Note that G may not be connected . ; Create a color array to store colors assigned to all veritces . Vertex number is used as index in this array . The value ' - 1' of colorArr [ i ] is used to indicate that no color is assigned to vertex ' i ' . The value 1 is used to indicate first color is assigned and value 0 indicates second color is assigned . ; One by one check all not yet colored vertices . ; Returns true if G can be divided into two Cliques , else false . ; Find complement of G [ ] [ ] All values are complemented except diagonal ones ; Return true if complement is Bipartite else false . ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int V = 5 ; bool isBipartiteUtil ( int G [ ] [ V ] , int src , int colorArr [ ] ) { colorArr [ src ] = 1 ; queue < int > q ; q . push ( src ) ; while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop ( ) ; for ( int v = 0 ; v < V ; ++ v ) { if ( G [ u ] [ v ] && colorArr [ v ] == -1 ) { colorArr [ v ] = 1 - colorArr [ u ] ; q . push ( v ) ; } else if ( G [ u ] [ v ] && colorArr [ v ] == colorArr [ u ] ) return false ; } } return true ; } bool isBipartite ( int G [ ] [ V ] ) { int colorArr [ V ] ; for ( int i = 0 ; i < V ; ++ i ) colorArr [ i ] = -1 ; for ( int i = 0 ; i < V ; i ++ ) if ( colorArr [ i ] == -1 ) if ( isBipartiteUtil ( G , i , colorArr ) == false ) return false ; return true ; } bool canBeDividedinTwoCliques ( int G [ ] [ V ] ) { int GC [ V ] [ V ] ; for ( int i = 0 ; i < V ; i ++ ) for ( int j = 0 ; j < V ; j ++ ) GC [ i ] [ j ] = ( i != j ) ? ! G [ i ] [ j ] : 0 ; return isBipartite ( GC ) ; } int main ( ) { int G [ ] [ V ] = { { 0 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 0 , 0 } , { 1 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 0 , 1 } , { 0 , 0 , 0 , 1 , 0 } } ; canBeDividedinTwoCliques ( G ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Check whether given degrees of vertices represent a Graph or Tree | C ++ program to check whether input degree sequence is graph or tree ; Function returns true for tree false for graph ; Find sum of all degrees ; Graph is tree if sum is equal to 2 ( n - 1 ) ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int degree [ ] , int n ) { int deg_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) deg_sum += degree [ i ] ; return ( 2 * ( n - 1 ) == deg_sum ) ; } int main ( ) { int n = 5 ; int degree [ ] = { 2 , 3 , 1 , 1 , 1 } ; if ( check ( degree , n ) ) cout << " Tree " ; else cout << " Graph " ; return 0 ; } |
Finding minimum vertex cover size of a graph using binary search | A C ++ program to find size of minimum vertex cover using Binary Search ; Global array to store the graph Note : since the array is global , all the elements are 0 initially ; Returns true if there is a possible subset of size ' k ' that can be a vertex cover ; Set has first ' k ' bits high initially ; to mark the edges covered in each subset of size ' k ' ; Reset visited array for every subset of vertices ; set counter for number of edges covered from this subset of vertices to zero ; selected vertex cover is the indices where ' set ' has its bit high ; Mark all edges emerging out of this vertex visited ; If the current subset covers all the edges ; Generate previous combination with k bits high set & - set = ( 1 << last bit high in set ) ; Returns answer to graph stored in gr [ ] [ ] ; Binary search the answer ; at the end of while loop both left and right will be equal , / as when they are not , the while loop won 't exit the minimum size vertex cover = left = right ; Inserts an edge in the graph ; Undirected graph ; Driver code ; 6 / 1 -- -- - 5 vertex cover = { 1 , 2 } / | \ 3 | \ \ | \ 2 4 ; Let us create another graph ; 2 -- -- 4 -- -- 6 / | | 1 | | vertex cover = { 2 , 3 , 4 } \ | | 3 -- -- 5 | #include <bits/stdc++.h> NEW_LINE #define maxn 25 NEW_LINE using namespace std ; bool gr [ maxn ] [ maxn ] ; bool isCover ( int V , int k , int E ) { int set = ( 1 << k ) - 1 ; int limit = ( 1 << V ) ; bool vis [ maxn ] [ maxn ] ; while ( set < limit ) { memset ( vis , 0 , sizeof vis ) ; int cnt = 0 ; for ( int j = 1 , v = 1 ; j < limit ; j = j << 1 , v ++ ) { if ( set & j ) { for ( int k = 1 ; k <= V ; k ++ ) { if ( gr [ v ] [ k ] && ! vis [ v ] [ k ] ) { vis [ v ] [ k ] = 1 ; vis [ k ] [ v ] = 1 ; cnt ++ ; } } } } if ( cnt == E ) return true ; int c = set & - set ; int r = set + c ; set = ( ( ( r ^ set ) >> 2 ) / c ) | r ; } return false ; } int findMinCover ( int n , int m ) { int left = 1 , right = n ; while ( right > left ) { int mid = ( left + right ) >> 1 ; if ( isCover ( n , mid , m ) == false ) left = mid + 1 ; else right = mid ; } return left ; } void insertEdge ( int u , int v ) { gr [ u ] [ v ] = 1 ; gr [ v ] [ u ] = 1 ; } int main ( ) { int V = 6 , E = 6 ; insertEdge ( 1 , 2 ) ; insertEdge ( 2 , 3 ) ; insertEdge ( 1 , 3 ) ; insertEdge ( 1 , 4 ) ; insertEdge ( 1 , 5 ) ; insertEdge ( 1 , 6 ) ; cout << " Minimum β size β of β a β vertex β cover β = β " << findMinCover ( V , E ) << endl ; memset ( gr , 0 , sizeof gr ) ; V = 6 , E = 7 ; insertEdge ( 1 , 2 ) ; insertEdge ( 1 , 3 ) ; insertEdge ( 2 , 3 ) ; insertEdge ( 2 , 4 ) ; insertEdge ( 3 , 5 ) ; insertEdge ( 4 , 5 ) ; insertEdge ( 4 , 6 ) ; cout << " Minimum β size β of β a β vertex β cover β = β " << findMinCover ( V , E ) << endl ; return 0 ; } |
Morris traversal for Preorder | C ++ program for Morris Preorder traversal ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Preorder traversal without recursion and without stack ; If left child is null , print the current node data . Move to right child . ; Find inorder predecessor ; If the right child of inorder predecessor already points to this node ; If right child doesn 't point to this node, then print this node and make right child point to this node ; Function for sStandard preorder traversal ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left , * right ; } ; node * newNode ( int data ) { node * temp = new node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void morrisTraversalPreorder ( node * root ) { while ( root ) { if ( root -> left == NULL ) { cout << root -> data << " β " ; root = root -> right ; } else { node * current = root -> left ; while ( current -> right && current -> right != root ) current = current -> right ; if ( current -> right == root ) { current -> right = NULL ; root = root -> right ; } else { cout << root -> data << " β " ; current -> right = root ; root = root -> left ; } } } } void preorder ( node * root ) { if ( root ) { cout << root -> data << " β " ; preorder ( root -> left ) ; preorder ( root -> right ) ; } } int main ( ) { node * root = NULL ; root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 11 ) ; morrisTraversalPreorder ( root ) ; cout << endl ; preorder ( root ) ; return 0 ; } |
Sum of dependencies in a graph | C ++ program to find the sum of dependencies ; To add an edge ; find the sum of all dependencies ; just find the size at each vector 's index ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void addEdge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; } int findSum ( vector < int > adj [ ] , int V ) { int sum = 0 ; for ( int u = 0 ; u < V ; u ++ ) sum += adj [ u ] . size ( ) ; return sum ; } int main ( ) { int V = 4 ; vector < int > adj [ V ] ; addEdge ( adj , 0 , 2 ) ; addEdge ( adj , 0 , 3 ) ; addEdge ( adj , 1 , 3 ) ; addEdge ( adj , 2 , 3 ) ; cout << " Sum β of β dependencies β is β " << findSum ( adj , V ) ; return 0 ; } |
Linked List | Set 2 ( Inserting a node ) | Given a reference ( pointer to pointer ) to the head of a list and an int , inserts a new node on the front of the list . ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new node as head ; 4. move the head to point to the new node | void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } |
Linked List | Set 2 ( Inserting a node ) | Given a node prev_node , insert a new node after the given prev_node ; 1. Check if the given prev_node is NULL ; 2. Allocate the Node & 3. Put in the data ; 4. Make next of new node as next of prev_node ; 5. move the next of prev_node as new_node | void insertAfter ( Node * prev_node , int new_data ) { if ( prev_node == NULL ) { cout << " the β given β previous β node β cannot β be β NULL " ; return ; } Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = prev_node -> next ; prev_node -> next = new_node ; } |
Iterative Preorder Traversal | C ++ program to implement iterative preorder traversal ; A binary tree node has data , left child and right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; An iterative process to print preorder traversal of Binary tree ; Base Case ; Create an empty stack and push root to it ; Pop all items one by one . Do following for every popped item a ) print it b ) push its right child c ) push its left child Note that right child is pushed first so that left is processed first ; Pop the top item from stack and print it ; Push right and left children of the popped node to stack ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; struct node * newNode ( int data ) { struct node * node = new struct node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } void iterativePreorder ( node * root ) { if ( root == NULL ) return ; stack < node * > nodeStack ; nodeStack . push ( root ) ; while ( nodeStack . empty ( ) == false ) { struct node * node = nodeStack . top ( ) ; printf ( " % d β " , node -> data ) ; nodeStack . pop ( ) ; if ( node -> right ) nodeStack . push ( node -> right ) ; if ( node -> left ) nodeStack . push ( node -> left ) ; } } int main ( ) { struct node * root = newNode ( 10 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 2 ) ; iterativePreorder ( root ) ; return 0 ; } |
Iterative Preorder Traversal | ; Tree Node ; Iterative function to do Preorder traversal of the tree ; start from root node ( set current node to root node ) ; run till stack is not empty or current is not NULL ; Print left children while exist and keep pushing right into the stack . ; We reach when curr is NULL , so We take out a right child from stack ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; Node ( int data ) { this -> data = data ; this -> left = this -> right = NULL ; } } ; void preorderIterative ( Node * root ) { if ( root == NULL ) return ; stack < Node * > st ; Node * curr = root ; while ( ! st . empty ( ) curr != NULL ) { while ( curr != NULL ) { cout << curr -> data << " β " ; if ( curr -> right ) st . push ( curr -> right ) ; curr = curr -> left ; } if ( st . empty ( ) == false ) { curr = st . top ( ) ; st . pop ( ) ; } } } int main ( ) { Node * root = new Node ( 10 ) ; root -> left = new Node ( 20 ) ; root -> right = new Node ( 30 ) ; root -> left -> left = new Node ( 40 ) ; root -> left -> left -> left = new Node ( 70 ) ; root -> left -> right = new Node ( 50 ) ; root -> right -> left = new Node ( 60 ) ; root -> left -> left -> right = new Node ( 80 ) ; preorderIterative ( root ) ; return 0 ; } |
Write a function that counts the number of times a given int occurs in a Linked List | C ++ program to count occurrences in a linked list using recursion ; Link list node ; global variable for counting frequeancy of given element k ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node ; link the old list off the new node ; move the head to point to the new node ; Counts the no . of occurrences of a node ( search_for ) in a linked list ( head ) ; Driver program to test count function ; Start with the empty list ; Use push ( ) to construct below list 1 -> 2 -> 1 -> 3 -> 1 ; Check the count function | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; int frequency = 0 ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int count ( struct Node * head , int key ) { if ( head == NULL ) return frequency ; if ( head -> data == key ) frequency ++ ; return count ( head -> next , key ) ; } int main ( ) { struct Node * head = NULL ; push ( & head , 1 ) ; push ( & head , 3 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; cout << " count β of β 1 β is β " << count ( head , 1 ) ; return 0 ; } |
Write a function that counts the number of times a given int occurs in a Linked List | Counts the no . of occurrences of a node ( search_for ) in a linked list ( head ) | int count ( struct Node * head , int key ) { if ( head == NULL ) return 0 ; if ( head -> data == key ) return 1 + count ( head -> next , key ) ; return count ( head -> next , key ) ; } |
Detect loop in a linked list | C ++ program to detect loop in a linked list ; Link list node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Returns true if there is a loop in linked list else returns false . ; If this node is already traverse it means there is a cycle ( Because you we encountering the node for the second time ) . ; If we are seeing the node for the first time , mark its flag as 1 ; Driver program to test above function ; Start with the empty list ; Create a loop for testing | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; int flag ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> flag = 0 ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } bool detectLoop ( struct Node * h ) { while ( h != NULL ) { if ( h -> flag == 1 ) return true ; h -> flag = 1 ; h = h -> next ; } return false ; } int main ( ) { struct Node * head = NULL ; push ( & head , 20 ) ; push ( & head , 4 ) ; push ( & head , 15 ) ; push ( & head , 10 ) ; head -> next -> next -> next -> next = head ; if ( detectLoop ( head ) ) cout << " Loop β found " ; else cout << " No β Loop " ; return 0 ; } |
Detect loop in a linked list | C ++ program to detect loop in a linked list ; Link list node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver code ; Start with the empty list ; Create a loop for testing | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int detectLoop ( Node * list ) { Node * slow_p = list , * fast_p = list ; while ( slow_p && fast_p && fast_p -> next ) { slow_p = slow_p -> next ; fast_p = fast_p -> next -> next ; if ( slow_p == fast_p ) { return 1 ; } } return 0 ; } int main ( ) { Node * head = NULL ; push ( & head , 20 ) ; push ( & head , 4 ) ; push ( & head , 15 ) ; push ( & head , 10 ) ; head -> next -> next -> next -> next = head ; if ( detectLoop ( head ) ) cout << " Loop β found " ; else cout << " No β Loop " ; return 0 ; } |
Detect loop in a linked list | C ++ program to return first node of loop ; A utility function to print a linked list ; Function to detect first node of loop in a linked list that may contain loop ; Create a temporary node ; This condition is for the case when there is no loop ; Check if next is already pointing to temp ; Store the pointer to the next node in order to get to it in the next step ; Make next point to temp ; Get to the next node in the list ; Driver program to test above function ; Create a loop for testing ( 5 is pointing to 3 ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * next ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> next = NULL ; return temp ; } void printList ( Node * head ) { while ( head != NULL ) { cout << head -> key << " β " ; head = head -> next ; } cout << endl ; } bool detectLoop ( Node * head ) { Node * temp = new Node ; while ( head != NULL ) { if ( head -> next == NULL ) { return false ; } if ( head -> next == temp ) { return true ; } Node * nex = head -> next ; head -> next = temp ; head = nex ; } return false ; } int main ( ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; head -> next -> next -> next -> next -> next = head -> next -> next ; bool found = detectLoop ( head ) ; if ( found ) cout << " Loop β Found " ; else cout << " No β Loop " ; return 0 ; } |
Detect loop in a linked list | C ++ program to return first node of loop ; A utility function to print a linked list ; returns distance between first and last node every time * last node moves forwars ; counts no of nodes between first and last ; Function to detect first node of loop in a linked list that may contain loop ; Create a temporary node ; first always points to head ; last pointer initially points to head ; current_length stores no of nodes between current * position of first and last ; current_length stores no of nodes between previous * position of first and last ; set prev_length to current length then update the current length ; distance is calculated ; last node points the next node ; Driver program to test above function ; Create a loop for testing ( 5 is pointing to 3 ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * next ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> next = NULL ; return temp ; } void printList ( Node * head ) { while ( head != NULL ) { cout << head -> key << " β " ; head = head -> next ; } cout << endl ; } int distance ( Node * first , Node * last ) { int counter = 0 ; Node * curr ; curr = first ; while ( curr != last ) { counter += 1 ; curr = curr -> next ; } return counter + 1 ; } bool detectLoop ( Node * head ) { Node * temp = new Node ; Node * first , * last ; first = head ; last = head ; int current_length = 0 ; int prev_length = -1 ; while ( current_length > prev_length && last != NULL ) { prev_length = current_length ; current_length = distance ( first , last ) ; last = last -> next ; } if ( last == NULL ) { return false ; } else { return true ; } } int main ( ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; head -> next -> next -> next -> next -> next = head -> next -> next ; bool found = detectLoop ( head ) ; if ( found ) cout << " Loop β Found " ; else cout << " No β Loop β Found " ; return 0 ; } |
Remove duplicates from a sorted linked list | CPP program for the above approach ; Function to insert a node at the beginging of the linked * list ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to print nodes in a given linked list ; Function to remove duplicates ; Driver Code ; Created linked list will be 11 -> 11 -> 11 -> 13 -> 13 -> 20 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; Node ( ) { data = 0 ; next = NULL ; } } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " β " ; node = node -> next ; } } void removeDuplicates ( Node * head ) { unordered_map < int , bool > track ; Node * temp = head ; while ( temp ) { if ( track . find ( temp -> data ) == track . end ( ) ) { cout << temp -> data << " β " ; } track [ temp -> data ] = true ; temp = temp -> next ; } } int main ( ) { Node * head = NULL ; push ( & head , 20 ) ; push ( & head , 13 ) ; push ( & head , 13 ) ; push ( & head , 11 ) ; push ( & head , 11 ) ; push ( & head , 11 ) ; cout << " Linked β list β before β duplicate β removal β " ; printList ( head ) ; cout << " Linked list after duplicate removal " ; removeDuplicates ( head ) ; return 0 ; } |
Swap nodes in a linked list without swapping data | This program swaps the nodes of linked list rather than swapping the field from the nodes . ; Function to swap nodes x and y in linked list by changing links ; Nothing to do if x and y are same ; Search for x ( keep track of prevX and CurrX ; Search for y ( keep track of prevY and CurrY ; If either x or y is not present , nothing to do ; If x is not head of linked list ; Else make y as new head ; If y is not head of linked list ; Else make x as new head ; Swap next pointers ; Function to add a node at the beginning of List ; allocate node and put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to print nodes in a given linked list ; Driver program to test above function ; The constructed linked list is : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void swapNodes ( Node * * head_ref , int x , int y ) { if ( x == y ) return ; Node * prevX = NULL , * currX = * head_ref ; while ( currX && currX -> data != x ) { prevX = currX ; currX = currX -> next ; } Node * prevY = NULL , * currY = * head_ref ; while ( currY && currY -> data != y ) { prevY = currY ; currY = currY -> next ; } if ( currX == NULL currY == NULL ) return ; if ( prevX != NULL ) prevX -> next = currY ; else * head_ref = currY ; if ( prevY != NULL ) prevY -> next = currX ; else * head_ref = currX ; Node * temp = currY -> next ; currY -> next = currX -> next ; currX -> next = temp ; } void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " β " ; node = node -> next ; } } int main ( ) { Node * start = NULL ; push ( & start , 7 ) ; push ( & start , 6 ) ; push ( & start , 5 ) ; push ( & start , 4 ) ; push ( & start , 3 ) ; push ( & start , 2 ) ; push ( & start , 1 ) ; cout << " Linked β list β before β calling β swapNodes ( ) β " ; printList ( start ) ; swapNodes ( & start , 4 , 3 ) ; cout << " Linked list after calling swapNodes ( ) " ; printList ( start ) ; return 0 ; } |
Postorder traversal of Binary Tree without recursion and without stack | CPP program or postorder traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Visited left subtree ; Visited right subtree ; Print node ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; void postorder ( struct Node * head ) { struct Node * temp = head ; unordered_set < Node * > visited ; while ( temp && visited . find ( temp ) == visited . end ( ) ) { if ( temp -> left && visited . find ( temp -> left ) == visited . end ( ) ) temp = temp -> left ; else if ( temp -> right && visited . find ( temp -> right ) == visited . end ( ) ) temp = temp -> right ; else { printf ( " % d β " , temp -> data ) ; visited . insert ( temp ) ; temp = head ; } } } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct Node * root = newNode ( 8 ) ; root -> left = newNode ( 3 ) ; root -> right = newNode ( 10 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 4 ) ; root -> left -> right -> right = newNode ( 7 ) ; root -> right -> right = newNode ( 14 ) ; root -> right -> right -> left = newNode ( 13 ) ; postorder ( root ) ; return 0 ; } |
Postorder traversal of Binary Tree without recursion and without stack | CPP program or postorder traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Visited left subtree ; Visited right subtree ; Print node ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; bool visited ; } ; void postorder ( struct Node * head ) { struct Node * temp = head ; while ( temp && temp -> visited == false ) { if ( temp -> left && temp -> left -> visited == false ) temp = temp -> left ; else if ( temp -> right && temp -> right -> visited == false ) temp = temp -> right ; else { printf ( " % d β " , temp -> data ) ; temp -> visited = true ; temp = head ; } } } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; node -> visited = false ; return ( node ) ; } int main ( ) { struct Node * root = newNode ( 8 ) ; root -> left = newNode ( 3 ) ; root -> right = newNode ( 10 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 4 ) ; root -> left -> right -> right = newNode ( 7 ) ; root -> right -> right = newNode ( 14 ) ; root -> right -> right -> left = newNode ( 13 ) ; postorder ( root ) ; return 0 ; } |
Check if a linked list is Circular Linked List | C ++ program to check if linked list is circular ; Link list Node ; This function returns true if given linked list is circular , else false . ; An empty linked list is circular ; Next of head ; This loop would stop in both cases ( 1 ) If Circular ( 2 ) Not circular ; If loop stopped because of circular condition ; Utility function to create a new node . ; Driver program to test above function ; Start with the empty list ; Making linked list circular | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; bool isCircular ( struct Node * head ) { if ( head == NULL ) return true ; struct Node * node = head -> next ; while ( node != NULL && node != head ) node = node -> next ; return ( node == head ) ; } Node * newNode ( int data ) { struct Node * temp = new Node ; temp -> data = data ; temp -> next = NULL ; return temp ; } int main ( ) { struct Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; isCircular ( head ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; head -> next -> next -> next -> next = head ; isCircular ( head ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; } |
Circular Singly Linked List | Insertion | ; This function is only for empty list ; Creating a node dynamically . ; Assigning the data . ; Note : list was empty . We link single node to itself . | struct Node * addToEmpty ( struct Node * last , int data ) { if ( last != NULL ) return last ; struct Node * temp = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; temp -> data = data ; last = temp ; temp -> next = last ; return last ; } |
Circular Singly Linked List | Insertion | ; Creating a node dynamically . ; Assigning the data . ; Adjusting the links . | struct Node * addBegin ( struct Node * last , int data ) { if ( last == NULL ) return addToEmpty ( last , data ) ; struct Node * temp = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; temp -> data = data ; temp -> next = last -> next ; last -> next = temp ; return last ; } |
Diagonal Traversal of Binary Tree | C ++ program for diagnoal traversal of Binary Tree ; Tree node ; root - root of the binary tree d - distance of current line from rightmost - topmost slope . diagonalPrint - multimap to store Diagonal elements ( Passed by Reference ) ; Base case ; Store all nodes of same line together as a vector ; Increase the vertical distance if left child ; Vertical distance remains same for right child ; Print diagonal traversal of given binary tree ; create a map of vectors to store Diagonal elements ; Utility method to create a new node ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; void diagonalPrintUtil ( Node * root , int d , map < int , vector < int > > & diagonalPrint ) { if ( ! root ) return ; diagonalPrint [ d ] . push_back ( root -> data ) ; diagonalPrintUtil ( root -> left , d + 1 , diagonalPrint ) ; diagonalPrintUtil ( root -> right , d , diagonalPrint ) ; } void diagonalPrint ( Node * root ) { map < int , vector < int > > diagonalPrint ; diagonalPrintUtil ( root , 0 , diagonalPrint ) ; cout << " Diagonal β Traversal β of β binary β tree β : β STRNEWLINE " ; for ( auto it : diagonalPrint ) { vector < int > v = it . second ; for ( auto it : v ) cout << it << " β " ; cout << endl ; } } Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } int main ( ) { Node * root = newNode ( 8 ) ; root -> left = newNode ( 3 ) ; root -> right = newNode ( 10 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 6 ) ; root -> right -> right = newNode ( 14 ) ; root -> right -> right -> left = newNode ( 13 ) ; root -> left -> right -> left = newNode ( 4 ) ; root -> left -> right -> right = newNode ( 7 ) ; diagonalPrint ( root ) ; return 0 ; } |
Binary Tree ( Array implementation ) | C ++ implementation of tree using array numbering starting from 0 to n - 1. ; create root ; create left son of root ; create right son of root ; Print tree ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char tree [ 10 ] ; int root ( char key ) { if ( tree [ 0 ] != ' \0' ) cout << " Tree β already β had β root " ; else tree [ 0 ] = key ; return 0 ; } int set_left ( char key , int parent ) { if ( tree [ parent ] == ' \0' ) cout << " Can ' set child at " << ( parent * 2 ) + 1 << " β , β no β parent β found " ; else tree [ ( parent * 2 ) + 1 ] = key ; return 0 ; } int set_right ( char key , int parent ) { if ( tree [ parent ] == ' \0' ) cout << " Can ' set child at " << ( parent * 2 ) + 2 << " β , β no β parent β found " ; else tree [ ( parent * 2 ) + 2 ] = key ; return 0 ; } int print_tree ( ) { cout << " STRNEWLINE " ; for ( int i = 0 ; i < 10 ; i ++ ) { if ( tree [ i ] != ' \0' ) cout << tree [ i ] ; else cout << " - " ; } return 0 ; } int main ( ) { root ( ' A ' ) ; set_right ( ' C ' , 0 ) ; set_left ( ' D ' , 1 ) ; set_right ( ' E ' , 1 ) ; set_right ( ' F ' , 2 ) ; print_tree ( ) ; return 0 ; } |
Swap Kth node from beginning with Kth node from end in a Linked List | A C ++ program to swap Kth node from beginning with kth node from end ; A Linked List node ; Utility function to insert a node at the beginning ; Utility function for displaying linked list ; Utility function for calculating length of linked list ; Function for swapping kth nodes from both ends of linked list ; Count nodes in linked list ; Check if k is valid ; If x ( kth node from start ) and y ( kth node from end ) are same ; Find the kth node from the beginning of the linked list . We also find previous of kth node because we need to update next pointer of the previous . ; Similarly , find the kth node from end and its previous . kth node from end is ( n - k + 1 ) th node from beginning ; If x_prev exists , then new next of it will be y . Consider the case when y -> next is x , in this case , x_prev and y are same . So the statement " x _ prev - > next β = β y " creates a self loop . This self loop will be broken when we change y -> next . ; Same thing applies to y_prev ; Swap next pointers of x and y . These statements also break self loop if x -> next is y or y -> next is x ; Change head pointers when k is 1 or n ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * node ) { while ( node != NULL ) { cout << node -> data << " β " ; node = node -> next ; } cout << endl ; } int countNodes ( struct Node * s ) { int count = 0 ; while ( s != NULL ) { count ++ ; s = s -> next ; } return count ; } void swapKth ( struct Node * * head_ref , int k ) { int n = countNodes ( * head_ref ) ; if ( n < k ) return ; if ( 2 * k - 1 == n ) return ; Node * x = * head_ref ; Node * x_prev = NULL ; for ( int i = 1 ; i < k ; i ++ ) { x_prev = x ; x = x -> next ; } Node * y = * head_ref ; Node * y_prev = NULL ; for ( int i = 1 ; i < n - k + 1 ; i ++ ) { y_prev = y ; y = y -> next ; } if ( x_prev ) x_prev -> next = y ; if ( y_prev ) y_prev -> next = x ; Node * temp = x -> next ; x -> next = y -> next ; y -> next = temp ; if ( k == 1 ) * head_ref = y ; if ( k == n ) * head_ref = x ; } int main ( ) { struct Node * head = NULL ; for ( int i = 8 ; i >= 1 ; i -- ) push ( & head , i ) ; cout << " Original β Linked β List : β " ; printList ( head ) ; for ( int k = 1 ; k < 9 ; k ++ ) { swapKth ( & head , k ) ; cout << " Modified List for k = " printList ( head ) ; } return 0 ; } |
Find pairs with given sum in doubly linked list | C ++ program to find a pair with given sum x . ; structure of node of doubly linked list ; Function to find pair whose sum equal to given value x . ; Set two pointers , first to the beginning of DLL and second to the end of DLL . ; To track if we find a pair or not ; The loop terminates when two pointers cross each other ( second -> next == first ) , or they become same ( first == second ) ; pair found ; move first in forward direction ; move second in backward direction ; if pair is not present ; A utility function to insert a new node at the beginning of doubly linked list ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next , * prev ; } ; void pairSum ( struct Node * head , int x ) { struct Node * first = head ; struct Node * second = head ; while ( second -> next != NULL ) second = second -> next ; bool found = false ; while ( first != second && second -> next != first ) { if ( ( first -> data + second -> data ) == x ) { found = true ; cout << " ( " << first -> data << " , β " << second -> data << " ) " << endl ; first = first -> next ; second = second -> prev ; } else { if ( ( first -> data + second -> data ) < x ) first = first -> next ; else second = second -> prev ; } } if ( found == false ) cout << " No β pair β found " ; } void insert ( struct Node * * head , int data ) { struct Node * temp = new Node ; temp -> data = data ; temp -> next = temp -> prev = NULL ; if ( ! ( * head ) ) ( * head ) = temp ; else { temp -> next = * head ; ( * head ) -> prev = temp ; ( * head ) = temp ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 9 ) ; insert ( & head , 8 ) ; insert ( & head , 6 ) ; insert ( & head , 5 ) ; insert ( & head , 4 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; int x = 7 ; pairSum ( head , x ) ; return 0 ; } |
Iterative diagonal traversal of binary tree | C ++ program to construct string from binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node ; Iterative function to print diagonal view ; base case ; inbuilt queue of Treenode ; push root ; push delimiter ; if current is delimiter then insert another for next diagonal and cout nextline ; if queue is empty return ; output nextline ; push delimiter again ; if left child is present push into queue ; current equals to right child ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = ( Node * ) malloc ( sizeof ( Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void diagonalPrint ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; q . push ( NULL ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp == NULL ) { if ( q . empty ( ) ) return ; cout << endl ; q . push ( NULL ) ; } else { while ( temp ) { cout << temp -> data << " β " ; if ( temp -> left ) q . push ( temp -> left ) ; temp = temp -> right ; } } } } int main ( ) { Node * root = newNode ( 8 ) ; root -> left = newNode ( 3 ) ; root -> right = newNode ( 10 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 6 ) ; root -> right -> right = newNode ( 14 ) ; root -> right -> right -> left = newNode ( 13 ) ; root -> left -> right -> left = newNode ( 4 ) ; root -> left -> right -> right = newNode ( 7 ) ; diagonalPrint ( root ) ; } |
Count triplets in a sorted doubly linked list whose sum is equal to a given value x | C ++ implementation to count triplets in a sorted doubly linked list whose sum is equal to a given value ' x ' ; structure of node of doubly linked list ; function to count pairs whose sum equal to given ' value ' ; The loop terminates when either of two pointers become NULL , or they cross each other ( second -> next == first ) , or they become same ( first == second ) ; pair found ; increment count ; move first in forward direction ; move second in backward direction ; if sum is greater than ' value ' move second in backward direction ; else move first in forward direction ; required count of pairs ; function to count triplets in a sorted doubly linked list whose sum is equal to a given value ' x ' ; if list is empty ; get pointer to the last node of the doubly linked list ; traversing the doubly linked list ; for each current node ; count pairs with sum ( x - current -> data ) in the range first to last and add it to the ' count ' of triplets ; required count of triplets ; A utility function to insert a new node at the beginning of doubly linked list ; allocate node ; put in the data ; Driver program to test above ; start with an empty doubly linked list ; insert values in sorted order | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next , * prev ; } ; int countPairs ( struct Node * first , struct Node * second , int value ) { int count = 0 ; while ( first != NULL && second != NULL && first != second && second -> next != first ) { if ( ( first -> data + second -> data ) == value ) { count ++ ; first = first -> next ; second = second -> prev ; } else if ( ( first -> data + second -> data ) > value ) second = second -> prev ; else first = first -> next ; } return count ; } int countTriplets ( struct Node * head , int x ) { if ( head == NULL ) return 0 ; struct Node * current , * first , * last ; int count = 0 ; last = head ; while ( last -> next != NULL ) last = last -> next ; for ( current = head ; current != NULL ; current = current -> next ) { first = current -> next ; count += countPairs ( first , last , x - current -> data ) ; } return count ; } void insert ( struct Node * * head , int data ) { struct Node * temp = new Node ( ) ; temp -> data = data ; temp -> next = temp -> prev = NULL ; if ( ( * head ) == NULL ) ( * head ) = temp ; else { temp -> next = * head ; ( * head ) -> prev = temp ; ( * head ) = temp ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 9 ) ; insert ( & head , 8 ) ; insert ( & head , 6 ) ; insert ( & head , 5 ) ; insert ( & head , 4 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; int x = 17 ; cout << " Count β = β " << countTriplets ( head , x ) ; return 0 ; } |
Remove duplicates from an unsorted doubly linked list | C ++ implementation to remove duplicates from an unsorted doubly linked list ; a node of the doubly linked list ; Function to delete a node in a Doubly Linked List . head_ref -- > pointer to head node pointer . del -- > pointer to node to be deleted . ; base case ; If node to be deleted is head node ; Change next only if node to be deleted is NOT the last node ; Change prev only if node to be deleted is NOT the first node ; function to remove duplicates from an unsorted doubly linked list ; if DLL is empty or if it contains only a single node ; pick elements one by one ; Compare the picked element with the rest of the elements ; if duplicate , then delete it ; store pointer to the node next to ' ptr2' ; delete node pointed to by ' ptr2' ; update ' ptr2' ; else simply move to the next node ; Function to insert a node at the beginning of the Doubly Linked List ; allocate node ; put in the data ; since we are adding at the beginning , prev is always NULL ; link the old list off the new node ; change prev of head node to new node ; move the head to point to the new node ; Function to print nodes in a given doubly linked list ; if list is empty ; Driver program to test above ; Create the doubly linked list : 8 < -> 4 < -> 4 < -> 6 < -> 4 < -> 8 < -> 4 < -> 10 < -> 12 < -> 12 ; remove duplicate nodes | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; struct Node * prev ; } ; void deleteNode ( struct Node * * head_ref , struct Node * del ) { if ( * head_ref == NULL del == NULL ) return ; if ( * head_ref == del ) * head_ref = del -> next ; if ( del -> next != NULL ) del -> next -> prev = del -> prev ; if ( del -> prev != NULL ) del -> prev -> next = del -> next ; free ( del ) ; } void removeDuplicates ( struct Node * * head_ref ) { if ( ( * head_ref ) == NULL || ( * head_ref ) -> next == NULL ) return ; struct Node * ptr1 , * ptr2 ; for ( ptr1 = * head_ref ; ptr1 != NULL ; ptr1 = ptr1 -> next ) { ptr2 = ptr1 -> next ; while ( ptr2 != NULL ) { if ( ptr1 -> data == ptr2 -> data ) { struct Node * next = ptr2 -> next ; deleteNode ( head_ref , ptr2 ) ; ptr2 = next ; } else ptr2 = ptr2 -> next ; } } } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> prev = NULL ; new_node -> next = ( * head_ref ) ; if ( ( * head_ref ) != NULL ) ( * head_ref ) -> prev = new_node ; ( * head_ref ) = new_node ; } void printList ( struct Node * head ) { if ( head == NULL ) cout << " Doubly β Linked β list β empty " ; while ( head != NULL ) { cout << head -> data << " β " ; head = head -> next ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 12 ) ; push ( & head , 10 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; push ( & head , 4 ) ; push ( & head , 6 ) ; push ( & head , 4 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; cout << " Original β Doubly β linked β list : n " ; printList ( head ) ; removeDuplicates ( & head ) ; cout << " Doubly linked list after " STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " removing duplicates : n " ; printList ( head ) ; return 0 ; } |
Remove duplicates from an unsorted doubly linked list | C ++ implementation to remove duplicates from an unsorted doubly linked list ; a node of the doubly linked list ; Function to delete a node in a Doubly Linked List . head_ref -- > pointer to head node pointer . del -- > pointer to node to be deleted . ; base case ; If node to be deleted is head node ; Change next only if node to be deleted is NOT the last node ; Change prev only if node to be deleted is NOT the first node ; function to remove duplicates from an unsorted doubly linked list ; if doubly linked list is empty ; unordered_set ' us ' implemented as hash table ; traverse up to the end of the list ; if current data is seen before ; store pointer to the node next to ' current ' node ; delete the node pointed to by ' current ' ; update ' current ' ; insert the current data in ' us ' ; move to the next node ; Function to insert a node at the beginning of the Doubly Linked List ; allocate node ; put in the data ; since we are adding at the beginning , prev is always NULL ; link the old list off the new node ; change prev of head node to new node ; move the head to point to the new node ; Function to print nodes in a given doubly linked list ; if list is empty ; Driver program to test above ; Create the doubly linked list : 8 < -> 4 < -> 4 < -> 6 < -> 4 < -> 8 < -> 4 < -> 10 < -> 12 < -> 12 ; remove duplicate nodes | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; struct Node * prev ; } ; void deleteNode ( struct Node * * head_ref , struct Node * del ) { if ( * head_ref == NULL del == NULL ) return ; if ( * head_ref == del ) * head_ref = del -> next ; if ( del -> next != NULL ) del -> next -> prev = del -> prev ; if ( del -> prev != NULL ) del -> prev -> next = del -> next ; free ( del ) ; } void removeDuplicates ( struct Node * * head_ref ) { if ( ( * head_ref ) == NULL ) return ; unordered_set < int > us ; struct Node * current = * head_ref , * next ; while ( current != NULL ) { if ( us . find ( current -> data ) != us . end ( ) ) { next = current -> next ; deleteNode ( head_ref , current ) ; current = next ; } else { us . insert ( current -> data ) ; current = current -> next ; } } } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> prev = NULL ; new_node -> next = ( * head_ref ) ; if ( ( * head_ref ) != NULL ) ( * head_ref ) -> prev = new_node ; ( * head_ref ) = new_node ; } void printList ( struct Node * head ) { if ( head == NULL ) cout << " Doubly β Linked β list β empty " ; while ( head != NULL ) { cout << head -> data << " β " ; head = head -> next ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 12 ) ; push ( & head , 10 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; push ( & head , 4 ) ; push ( & head , 6 ) ; push ( & head , 4 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; cout << " Original β Doubly β linked β list : n " ; printList ( head ) ; removeDuplicates ( & head ) ; cout << " Doubly linked list after " STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " removing duplicates : n " ; printList ( head ) ; return 0 ; } |
Sorted insert in a doubly linked list with head and tail pointers | C ++ program to insetail nodes in doubly linked list such that list remains in ascending order on printing from left to right ; A linked list node ; Function to insetail new node ; If first node to be insetailed in doubly linked list ; If node to be insetailed has value less than first node ; If node to be insetailed has value more than last node ; Find the node before which we need to insert p . ; Insert new node before temp ; Function to print nodes in from left to right ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : Node * prev ; int info ; Node * next ; } ; void nodeInsetail ( Node * * head , Node * * tail , int key ) { Node * p = new Node ( ) ; p -> info = key ; p -> next = NULL ; if ( ( * head ) == NULL ) { ( * head ) = p ; ( * tail ) = p ; ( * head ) -> prev = NULL ; return ; } if ( ( p -> info ) < ( ( * head ) -> info ) ) { p -> prev = NULL ; ( * head ) -> prev = p ; p -> next = ( * head ) ; ( * head ) = p ; return ; } if ( ( p -> info ) > ( ( * tail ) -> info ) ) { p -> prev = ( * tail ) ; ( * tail ) -> next = p ; ( * tail ) = p ; return ; } Node * temp = ( * head ) -> next ; while ( ( temp -> info ) < ( p -> info ) ) temp = temp -> next ; ( temp -> prev ) -> next = p ; p -> prev = temp -> prev ; temp -> prev = p ; p -> next = temp ; } void printList ( Node * temp ) { while ( temp != NULL ) { cout << temp -> info << " β " ; temp = temp -> next ; } } int main ( ) { Node * left = NULL , * right = NULL ; nodeInsetail ( & left , & right , 30 ) ; nodeInsetail ( & left , & right , 50 ) ; nodeInsetail ( & left , & right , 90 ) ; nodeInsetail ( & left , & right , 10 ) ; nodeInsetail ( & left , & right , 40 ) ; nodeInsetail ( & left , & right , 110 ) ; nodeInsetail ( & left , & right , 60 ) ; nodeInsetail ( & left , & right , 95 ) ; nodeInsetail ( & left , & right , 23 ) ; cout << " Doubly β linked β list β on β printing " " β from β left β to β right STRNEWLINE " ; printList ( left ) ; return 0 ; } |
Doubly Circular Linked List | Set 1 ( Introduction and Insertion ) | Function to insert at the end ; If the list is empty , create a single node circular and doubly list ; If list is not empty Find last node ; Create Node dynamically ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last | void insertEnd ( struct Node * * start , int value ) { if ( * start == NULL ) { struct Node * new_node = new Node ; new_node -> data = value ; new_node -> next = new_node -> prev = new_node ; * start = new_node ; return ; } Node * last = ( * start ) -> prev ; struct Node * new_node = new Node ; new_node -> data = value ; new_node -> next = * start ; ( * start ) -> prev = new_node ; new_node -> prev = last ; last -> next = new_node ; } |
Doubly Circular Linked List | Set 1 ( Introduction and Insertion ) | C ++ program to illustrate inserting a Node in a Cicular Doubly Linked list in begging , end and middle ; Structure of a Node ; Function to insert at the end ; If the list is empty , create a single node circular and doubly list ; Find last node ; Create Node dynamically ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last ; Function to insert Node at the beginning of the List , ; Pointer points to last Node ; Inserting the data ; setting up previous and next of new node ; Update next and previous pointers of start and last . ; Update start pointer ; Function to insert node with value as value1 . The new node is inserted after the node with with value2 ; Inserting the data ; Find node having value2 and next node of it ; insert new_node between temp and next . ; Driver program to test above functions ; Start with the empty list ; Insert 5. So linked list becomes 5 -> NULL ; Insert 4 at the beginning . So linked list becomes 4 -> 5 ; Insert 7 at the end . So linked list becomes 4 -> 5 -> 7 ; Insert 8 at the end . So linked list becomes 4 -> 5 -> 7 -> 8 ; Insert 6 , after 5. So linked list becomes 4 -> 5 -> 6 -> 7 -> 8 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; struct Node * prev ; } ; void insertEnd ( struct Node * * start , int value ) { if ( * start == NULL ) { struct Node * new_node = new Node ; new_node -> data = value ; new_node -> next = new_node -> prev = new_node ; * start = new_node ; return ; } Node * last = ( * start ) -> prev ; struct Node * new_node = new Node ; new_node -> data = value ; new_node -> next = * start ; ( * start ) -> prev = new_node ; new_node -> prev = last ; last -> next = new_node ; } void insertBegin ( struct Node * * start , int value ) { struct Node * last = ( * start ) -> prev ; struct Node * new_node = new Node ; new_node -> data = value ; new_node -> next = * start ; new_node -> prev = last ; last -> next = ( * start ) -> prev = new_node ; * start = new_node ; } void insertAfter ( struct Node * * start , int value1 , int value2 ) { struct Node * new_node = new Node ; new_node -> data = value1 ; struct Node * temp = * start ; while ( temp -> data != value2 ) temp = temp -> next ; struct Node * next = temp -> next ; temp -> next = new_node ; new_node -> prev = temp ; new_node -> next = next ; next -> prev = new_node ; } void display ( struct Node * start ) { struct Node * temp = start ; printf ( " Traversal in forward direction " while ( temp -> next != start ) { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; } printf ( " % d β " , temp -> data ) ; printf ( " Traversal in reverse direction " Node * last = start -> prev ; temp = last ; while ( temp -> prev != last ) { printf ( " % d β " , temp -> data ) ; temp = temp -> prev ; } printf ( " % d β " , temp -> data ) ; } int main ( ) { struct Node * start = NULL ; insertEnd ( & start , 5 ) ; insertBegin ( & start , 4 ) ; insertEnd ( & start , 7 ) ; insertEnd ( & start , 8 ) ; insertAfter ( & start , 6 , 5 ) ; printf ( " Created β circular β doubly β linked β list β is : β " ) ; display ( start ) ; return 0 ; } |
Boundary Traversal of binary tree | C program for boundary traversal of a binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A simple function to print leaf nodes of a binary tree ; Print it if it is a leaf node ; A function to print all left boundary nodes , except a leaf node . Print the nodes in TOP DOWN manner ; to ensure top down order , print the node before calling itself for left subtree ; do nothing if it is a leaf node , this way we avoid duplicates in output ; A function to print all right boundary nodes , except a leaf node Print the nodes in BOTTOM UP manner ; to ensure bottom up order , first call for right subtree , then print this node ; do nothing if it is a leaf node , this way we avoid duplicates in output ; A function to do boundary traversal of a given binary tree ; Print the left boundary in top - down manner . ; Print all leaf nodes ; Print the right boundary in bottom - up manner ; A utility function to create a node ; Driver program to test above functions | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left , * right ; } ; void printLeaves ( struct node * root ) { if ( root == NULL ) return ; printLeaves ( root -> left ) ; if ( ! ( root -> left ) && ! ( root -> right ) ) printf ( " % d β " , root -> data ) ; printLeaves ( root -> right ) ; } void printBoundaryLeft ( struct node * root ) { if ( root == NULL ) return ; if ( root -> left ) { printf ( " % d β " , root -> data ) ; printBoundaryLeft ( root -> left ) ; } else if ( root -> right ) { printf ( " % d β " , root -> data ) ; printBoundaryLeft ( root -> right ) ; } } void printBoundaryRight ( struct node * root ) { if ( root == NULL ) return ; if ( root -> right ) { printBoundaryRight ( root -> right ) ; printf ( " % d β " , root -> data ) ; } else if ( root -> left ) { printBoundaryRight ( root -> left ) ; printf ( " % d β " , root -> data ) ; } } void printBoundary ( struct node * root ) { if ( root == NULL ) return ; printf ( " % d β " , root -> data ) ; printBoundaryLeft ( root -> left ) ; printLeaves ( root -> left ) ; printLeaves ( root -> right ) ; printBoundaryRight ( root -> right ) ; } struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { struct node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; root -> right = newNode ( 22 ) ; root -> right -> right = newNode ( 25 ) ; printBoundary ( root ) ; return 0 ; } |
An interesting method to print reverse of a linked list | C program to print reverse of list ; Link list node ; Function to reverse the linked list ; For each node , print proper number of spaces before printing it ; use of carriage return to move back and print . ; Function to push a node ; Function to print linked list and find its length ; i for finding length of list ; Driver program to test above function ; Start with the empty list ; list nodes are as 6 5 4 3 2 1 ; printlist print the list and return the size of list ; print reverse list with help of carriage return function | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; void printReverse ( struct Node * * head_ref , int n ) { int j = 0 ; struct Node * current = * head_ref ; while ( current != NULL ) { for ( int i = 0 ; i < 2 * ( n - j ) ; i ++ ) printf ( " β " ) ; printf ( " % d \r " , current -> data ) ; current = current -> next ; j ++ ; } } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int printList ( struct Node * head ) { int i = 0 ; struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; i ++ ; } return i ; } int main ( ) { struct Node * head = NULL ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 3 ) ; push ( & head , 4 ) ; push ( & head , 5 ) ; push ( & head , 6 ) ; printf ( " Given β linked β list : STRNEWLINE " ) ; int n = printList ( head ) ; printf ( " Reversed Linked list : " printReverse ( & head , n ) ; printf ( " STRNEWLINE " ) ; return 0 ; } |
Practice questions for Linked List and Recursion | | struct Node { int data ; struct Node * next ; } ; |
Practice questions for Linked List and Recursion | | void fun1 ( struct Node * head ) { if ( head == NULL ) return ; fun1 ( head -> next ) ; cout << head -> data << " β " ; } |
Practice questions for Linked List and Recursion | | void fun2 ( struct Node * head ) { if ( head == NULL ) return ; cout << head -> data << " β " ; if ( head -> next != NULL ) fun2 ( head -> next -> next ) ; cout << head -> data << " β " ; } |
Practice questions for Linked List and Recursion | ; A linked list node ; Prints a linked list in reverse manner ; prints alternate nodes of a Linked List , first from head to end , and then from end to head . ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver code ; Start with the empty list ; Using push ( ) to construct below list 1 -> 2 -> 3 -> 4 -> 5 | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void fun1 ( Node * head ) { if ( head == NULL ) return ; fun1 ( head -> next ) ; cout << head -> data << " β " ; } void fun2 ( Node * start ) { if ( start == NULL ) return ; cout << start -> data << " β " ; if ( start -> next != NULL ) fun2 ( start -> next -> next ) ; cout << start -> data << " β " ; } void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { Node * head = NULL ; push ( & head , 5 ) ; push ( & head , 4 ) ; push ( & head , 3 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; cout << " Output β of β fun1 ( ) β for β list β 1 - > 2 - > 3 - > 4 - > 5 β STRNEWLINE " ; fun1 ( head ) ; cout << " Output of fun2 ( ) for list 1 -> 2 -> 3 -> 4 -> 5 " ; fun2 ( head ) ; return 0 ; } |
Density of Binary Tree in One Traversal | C ++ program to find density of a binary tree ; A binary tree node ; Helper function to allocates a new node ; Function to compute height and size of a binary tree ; compute height of each subtree ; increase size by 1 ; return larger of the two ; function to calculate density of a binary tree ; To store size ; Finds height and size ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } int heighAndSize ( Node * node , int & size ) { if ( node == NULL ) return 0 ; int l = heighAndSize ( node -> left , size ) ; int r = heighAndSize ( node -> right , size ) ; size ++ ; return ( l > r ) ? l + 1 : r + 1 ; } float density ( Node * root ) { if ( root == NULL ) return 0 ; int size = 0 ; int _height = heighAndSize ( root , size ) ; return ( float ) size / _height ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; printf ( " Density β of β given β binary β tree β is β % f " , density ( root ) ) ; return 0 ; } |
Given only a pointer / reference to a node to be deleted in a singly linked list , how do you delete it ? | | void deleteNode ( Node * node ) { * node = * ( node -> next ) ; } |
Squareroot ( n ) | C ++ program to find sqrt ( n ) 'th node of a linked list ; Linked list node ; Function to get the sqrt ( n ) th node of a linked list ; Traverse the list ; check if j = sqrt ( i ) ; for first node ; increment j if j = sqrt ( i ) ; return node 's data ; function to add a new node at the beginning of the list ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver program to test above function ; Start with the empty list | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; int printsqrtn ( Node * head ) { Node * sqrtn = NULL ; int i = 1 , j = 1 ; while ( head != NULL ) { if ( i == j * j ) { if ( sqrtn == NULL ) sqrtn = head ; else sqrtn = sqrtn -> next ; j ++ ; } i ++ ; head = head -> next ; } return sqrtn -> data ; } void print ( Node * head ) { while ( head != NULL ) { cout << head -> data << " β " ; head = head -> next ; } cout << endl ; } void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { Node * head = NULL ; push ( & head , 40 ) ; push ( & head , 30 ) ; push ( & head , 20 ) ; push ( & head , 10 ) ; cout << " Given β linked β list β is : " ; print ( head ) ; cout << " sqrt ( n ) th β node β is β " << printsqrtn ( head ) ; return 0 ; } |
Find the fractional ( or n / k | C ++ program to find fractional node in a linked list ; Linked list node ; Function to create a new node with given data ; Function to find fractional node in the linked list ; Corner cases ; Traverse the given list ; For every k nodes , we move fractionalNode one step ahead . ; First time we see a multiple of k ; A utility function to print a linked list ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE struct Node { int data ; Node * next ; } ; Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } Node * fractionalNodes ( Node * head , int k ) { if ( k <= 0 head == NULL ) return NULL ; Node * fractionalNode = NULL ; int i = 0 ; for ( Node * temp = head ; temp != NULL ; temp = temp -> next ) { if ( i % k == 0 ) { if ( fractionalNode == NULL ) fractionalNode = head ; else fractionalNode = fractionalNode -> next ; } i ++ ; } return fractionalNode ; } void printList ( Node * node ) { while ( node != NULL ) { printf ( " % d β " , node -> data ) ; node = node -> next ; } printf ( " STRNEWLINE " ) ; } int main ( void ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; int k = 2 ; printf ( " List β is β " ) ; printList ( head ) ; Node * answer = fractionalNodes ( head , k ) ; printf ( " Fractional node is " printf ( " % d STRNEWLINE " , answer -> data ) ; return 0 ; } |
Find modular node in a linked list | C ++ program to find modular node in a linked list ; Linked list node ; Function to create a new node with given data ; Function to find modular node in the linked list ; Corner cases ; Traverse the given list ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE struct Node { int data ; Node * next ; } ; Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } Node * modularNode ( Node * head , int k ) { if ( k <= 0 head == NULL ) return NULL ; int i = 1 ; Node * modularNode = NULL ; for ( Node * temp = head ; temp != NULL ; temp = temp -> next ) { if ( i % k == 0 ) modularNode = temp ; i ++ ; } return modularNode ; } int main ( void ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; int k = 2 ; Node * answer = modularNode ( head , k ) ; printf ( " Modular node is " if ( answer != NULL ) printf ( " % d STRNEWLINE " , answer -> data ) ; else printf ( " null STRNEWLINE " ) ; return 0 ; } |
Modify contents of Linked List | C ++ implementation to modify the contents of the linked list ; Linked list node ; Function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list at the end of the new node ; move the head to point to the new node ; Split the nodes of the given list into front and back halves , and return the two lists using the reference parameters . Uses the fast / slow pointer strategy . ; Advance ' fast ' two nodes , and advance ' slow ' one node ; ' slow ' is before the midpoint in the list , so split it in two at that point . ; Function to reverse the linked list ; perfrom the required subtraction operation on the 1 st half of the linked list ; traversing both the lists simultaneously ; subtraction operation and node data modification ; function to concatenate the 2 nd ( back ) list at the end of the 1 st ( front ) list and returns the head of the new list ; function to modify the contents of the linked list ; if list is empty or contains only single node ; split the list into two halves front and back lists ; reverse the 2 nd ( back ) list ; modify the contents of 1 st half ; agains reverse the 2 nd ( back ) list ; concatenating the 2 nd list back to the end of the 1 st list ; pointer to the modified list ; function to print the linked list ; Driver program to test above ; creating the linked list ; modify the linked list ; print the modified linked list | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printList ( struct Node * ) ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = * head_ref ; * head_ref = new_node ; } void frontAndBackSplit ( struct Node * head , struct Node * * front_ref , struct Node * * back_ref ) { Node * slow , * fast ; slow = head ; fast = head -> next ; while ( fast != NULL ) { fast = fast -> next ; if ( fast != NULL ) { slow = slow -> next ; fast = fast -> next ; } } * front_ref = head ; * back_ref = slow -> next ; slow -> next = NULL ; } void reverseList ( struct Node * * head_ref ) { struct Node * current , * prev , * next ; current = * head_ref ; prev = NULL ; while ( current != NULL ) { next = current -> next ; current -> next = prev ; prev = current ; current = next ; } * head_ref = prev ; } void modifyTheContentsOf1stHalf ( struct Node * front , struct Node * back ) { while ( back != NULL ) { front -> data = front -> data - back -> data ; front = front -> next ; back = back -> next ; } } struct Node * concatFrontAndBackList ( struct Node * front , struct Node * back ) { struct Node * head = front ; while ( front -> next != NULL ) front = front -> next ; front -> next = back ; return head ; } struct Node * modifyTheList ( struct Node * head ) { if ( ! head head -> next == NULL ) return head ; struct Node * front , * back ; frontAndBackSplit ( head , & front , & back ) ; reverseList ( & back ) ; modifyTheContentsOf1stHalf ( front , back ) ; reverseList ( & back ) ; head = concatFrontAndBackList ( front , back ) ; return head ; } void printList ( struct Node * head ) { if ( ! head ) return ; while ( head -> next != NULL ) { cout << head -> data << " β - > β " ; head = head -> next ; } cout << head -> data << endl ; } int main ( ) { struct Node * head = NULL ; push ( & head , 10 ) ; push ( & head , 7 ) ; push ( & head , 12 ) ; push ( & head , 8 ) ; push ( & head , 9 ) ; push ( & head , 2 ) ; head = modifyTheList ( head ) ; cout << " Modified β List : " << endl ; printList ( head ) ; return 0 ; } |
Modify contents of Linked List | C ++ implementation to modify the contents of the linked list ; Linked list node ; Function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list at the end of the new node ; move the head to point to the new node ; function to print the linked list ; Function to middle node of list . ; Advance ' fast ' two nodes , and advance ' slow ' one node ; If number of nodes are odd then update slow by slow -> next ; ; function to modify the contents of the linked list . ; Create Stack . ; Traverse the list by using temp until stack is empty . ; Driver program to test above ; creating the linked list ; Call Function to Find the starting point of second half of list . ; Call function to modify the contents of the linked list . ; print the modified linked list | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printList ( struct Node * ) ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = * head_ref ; * head_ref = new_node ; } void printList ( struct Node * head ) { if ( ! head ) return ; while ( head -> next != NULL ) { cout << head -> data << " β - > β " ; head = head -> next ; } cout << head -> data << endl ; } Node * find_mid ( Node * head ) { Node * temp = head , * slow = head , * fast = head ; while ( fast && fast -> next ) { slow = slow -> next ; fast = fast -> next -> next ; } if ( fast ) slow = slow -> next ; return slow ; } void modifyTheList ( struct Node * head , struct Node * slow ) { stack < int > s ; Node * temp = head ; while ( slow ) { s . push ( slow -> data ) ; slow = slow -> next ; } while ( ! s . empty ( ) ) { temp -> data = temp -> data - s . top ( ) ; temp = temp -> next ; s . pop ( ) ; } } int main ( ) { struct Node * head = NULL , * mid ; push ( & head , 10 ) ; push ( & head , 7 ) ; push ( & head , 12 ) ; push ( & head , 8 ) ; push ( & head , 9 ) ; push ( & head , 2 ) ; mid = find_mid ( head ) ; modifyTheList ( head , mid ) ; cout << " Modified β List : " << endl ; printList ( head ) ; return 0 ; } |
Binary Search Tree | Set 1 ( Search and Insertion ) | C function to search a given key in a given BST ; Base Cases : root is null or key is present at root ; Key is greater than root 's key ; Key is smaller than root 's key | struct node * search ( struct node * root , int key ) { if ( root == NULL root -> key == key ) return root ; if ( root -> key < key ) return search ( root -> right , key ) ; return search ( root -> left , key ) ; } |
Modify a binary tree to get preorder traversal using right pointers only | C code to modify binary tree for traversal using only right pointer ; A binary tree node has data , left child and right child ; function that allocates a new node with the given data and NULL left and right pointers . ; Function to modify tree ; if the left tree exists ; get the right - most of the original left subtree ; set root right to left subtree ; if the right subtree does not exists we are done ! ; set right pointer of right - most of the original left subtree ; modify the rightsubtree ; printing using right pointer only ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / \ 3 5 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new struct Node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } struct Node * modifytree ( struct Node * root ) { struct Node * right = root -> right ; struct Node * rightMost = root ; if ( root -> left ) { rightMost = modifytree ( root -> left ) ; root -> right = root -> left ; root -> left = NULL ; } if ( ! right ) return rightMost ; rightMost -> right = right ; rightMost = modifytree ( right ) ; return rightMost ; } void printpre ( struct Node * root ) { while ( root != NULL ) { cout << root -> data << " β " ; root = root -> right ; } } int main ( ) { struct Node * root = newNode ( 10 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; modifytree ( root ) ; printpre ( root ) ; return 0 ; } |
Construct BST from its given level order traversal | C ++ implementation to construct a BST from its level order traversal ; node of a BST ; function to get a new node ; Allocate memory ; put in the data ; function to construct a BST from its level order traversal ; function to print the inorder traversal ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } Node * LevelOrder ( Node * root , int data ) { if ( root == NULL ) { root = getNode ( data ) ; return root ; } if ( data <= root -> data ) root -> left = LevelOrder ( root -> left , data ) ; else root -> right = LevelOrder ( root -> right , data ) ; return root ; } Node * constructBst ( int arr [ ] , int n ) { if ( n == 0 ) return NULL ; Node * root = NULL ; for ( int i = 0 ; i < n ; i ++ ) root = LevelOrder ( root , arr [ i ] ) ; return root ; } void inorderTraversal ( Node * root ) { if ( ! root ) return ; inorderTraversal ( root -> left ) ; cout << root -> data << " β " ; inorderTraversal ( root -> right ) ; } int main ( ) { int arr [ ] = { 7 , 4 , 12 , 3 , 6 , 8 , 1 , 5 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Node * root = constructBst ( arr , n ) ; cout << " Inorder β Traversal : β " ; inorderTraversal ( root ) ; return 0 ; } |
Modify a binary tree to get preorder traversal using right pointers only | C ++ code to modify binary tree for traversal using only right pointer ; A binary tree node has data , left child and right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; An iterative process to set the right pointer of Binary tree ; Base Case ; Create an empty stack and push root to it ; Pop all items one by one . Do following for every popped item a ) print it b ) push its right child c ) push its left child Note that right child is pushed first so that left is processed first ; Pop the top item from stack ; Push right and left children of the popped node to stack ; check if some previous node exists ; set the right pointer of previous node to currrent ; set previous node as current node ; printing using right pointer only ; Driver code ; Constructed binary tree is 10 / \ 8 2 / \ 3 5 | #include <iostream> NEW_LINE #include <stack> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new struct Node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } void modifytree ( struct Node * root ) { if ( root == NULL ) return ; stack < Node * > nodeStack ; nodeStack . push ( root ) ; struct Node * pre = NULL ; while ( nodeStack . empty ( ) == false ) { struct Node * node = nodeStack . top ( ) ; nodeStack . pop ( ) ; if ( node -> right ) nodeStack . push ( node -> right ) ; if ( node -> left ) nodeStack . push ( node -> left ) ; if ( pre != NULL ) { pre -> right = node ; } pre = node ; } } void printpre ( struct Node * root ) { while ( root != NULL ) { cout << root -> data << " β " ; root = root -> right ; } } int main ( ) { struct Node * root = newNode ( 10 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; modifytree ( root ) ; printpre ( root ) ; return 0 ; } |
Check given array of size n can represent BST of n levels or not | C ++ program to Check given array can represent BST or not ; structure for Binary Node ; To create a Tree with n levels . We always insert new node to left if it is less than previous value . ; Please refer below post for details of this function . www . geeksforgeeks . org / a - program - to - check - if - a - binary - tree - is - bst - or - not / https : ; Allow only distinct values ; Returns tree if given array of size n can represent a BST of n levels . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * right , * left ; } ; Node * newNode ( int num ) { Node * temp = new Node ; temp -> key = num ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } Node * createNLevelTree ( int arr [ ] , int n ) { Node * root = newNode ( arr [ 0 ] ) ; Node * temp = root ; for ( int i = 1 ; i < n ; i ++ ) { if ( temp -> key > arr [ i ] ) { temp -> left = newNode ( arr [ i ] ) ; temp = temp -> left ; } else { temp -> right = newNode ( arr [ i ] ) ; temp = temp -> right ; } } return root ; } bool isBST ( Node * root , int min , int max ) { if ( root == NULL ) return true ; if ( root -> key < min root -> key > max ) return false ; return ( isBST ( root -> left , min , ( root -> key ) - 1 ) && isBST ( root -> right , ( root -> key ) + 1 , max ) ) ; } bool canRepresentNLevelBST ( int arr [ ] , int n ) { Node * root = createNLevelTree ( arr , n ) ; return isBST ( root , INT_MIN , INT_MAX ) ; } int main ( ) { int arr [ ] = { 512 , 330 , 78 , 11 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( canRepresentNLevelBST ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Check given array of size n can represent BST of n levels or not | C ++ program to Check given array can represent BST or not ; Driver code ; This element can be inserted to the right of the previous element , only if it is greater than the previous element and in the range . ; max remains same , update min ; This element can be inserted to the left of the previous element , only if it is lesser than the previous element and in the range . ; min remains same , update max ; if the loop completed successfully without encountering else condition | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int arr [ ] = { 5123 , 3300 , 783 , 1111 , 890 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = INT_MAX ; int min = INT_MIN ; bool flag = true ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] && arr [ i ] > min && arr [ i ] < max ) { min = arr [ i - 1 ] ; } else if ( arr [ i ] < arr [ i - 1 ] && arr [ i ] > min && arr [ i ] < max ) { max = arr [ i - 1 ] ; } else { flag = false ; break ; } } if ( flag ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Convert a normal BST to Balanced BST | C ++ program to convert a left unbalanced BST to a balanced BST ; A binary tree node has data , pointer to left child and a pointer to right child ; This function traverse the skewed binary tree and stores its nodes pointers in vector nodes [ ] ; Base case ; Store nodes in Inorder ( which is sorted order for BST ) ; Recursive function to construct binary tree ; base case ; Get the middle element and make it root ; Using index in Inorder traversal , construct left and right subtress ; This functions converts an unbalanced BST to a balanced BST ; Store nodes of given BST in sorted order ; Constucts BST from nodes [ ] ; Utility function to create a new node ; Function to do preorder traversal of tree ; Driver program ; Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; void storeBSTNodes ( Node * root , vector < Node * > & nodes ) { if ( root == NULL ) return ; storeBSTNodes ( root -> left , nodes ) ; nodes . push_back ( root ) ; storeBSTNodes ( root -> right , nodes ) ; } Node * buildTreeUtil ( vector < Node * > & nodes , int start , int end ) { if ( start > end ) return NULL ; int mid = ( start + end ) / 2 ; Node * root = nodes [ mid ] ; root -> left = buildTreeUtil ( nodes , start , mid - 1 ) ; root -> right = buildTreeUtil ( nodes , mid + 1 , end ) ; return root ; } Node * buildTree ( Node * root ) { vector < Node * > nodes ; storeBSTNodes ( root , nodes ) ; int n = nodes . size ( ) ; return buildTreeUtil ( nodes , 0 , n - 1 ) ; } Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void preOrder ( Node * node ) { if ( node == NULL ) return ; printf ( " % d β " , node -> data ) ; preOrder ( node -> left ) ; preOrder ( node -> right ) ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 8 ) ; root -> left -> left = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 6 ) ; root -> left -> left -> left -> left = newNode ( 5 ) ; root = buildTree ( root ) ; printf ( " Preorder β traversal β of β balanced β " " BST β is β : β STRNEWLINE " ) ; preOrder ( root ) ; return 0 ; } |
Find the node with minimum value in a Binary Search Tree | C ++ program to find minimum value node in binary search Tree . ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Give a binary search tree and a number , inserts a new node with the given number in the correct place in the tree . Returns the new root pointer which the caller should then use ( the standard trick to avoid using reference parameters ) . ; 1. If the tree is empty , return a new , single node ; 2. Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the minimum data value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } struct node * insert ( struct node * node , int data ) { if ( node == NULL ) return ( newNode ( data ) ) ; else { if ( data <= node -> data ) node -> left = insert ( node -> left , data ) ; else node -> right = insert ( node -> right , data ) ; return node ; } } int minValue ( struct node * node ) { struct node * current = node ; while ( current -> left != NULL ) { current = current -> left ; } return ( current -> data ) ; } int main ( ) { struct node * root = NULL ; root = insert ( root , 4 ) ; insert ( root , 2 ) ; insert ( root , 1 ) ; insert ( root , 3 ) ; insert ( root , 6 ) ; insert ( root , 5 ) ; cout << " Minimum value in BST is " getchar ( ) ; return 0 ; } |
Check if the given array can represent Level Order Traversal of Binary Search Tree | C ++ implementation to check if the given array can represent Level Order Traversal of Binary Search Tree ; to store details of a node like node ' s β data , β ' min ' β and β ' max ' β to β obtain β the β range β of β values β where β node ' s left and right child 's should lie ; function to check if the given array can represent Level Order Traversal of Binary Search Tree ; if tree is empty ; queue to store NodeDetails ; index variable to access array elements ; node details for the root of the BST ; until there are no more elements in arr [ ] or queue is not empty ; extracting NodeDetails of a node from the queue ; check whether there are more elements in the arr [ ] and arr [ i ] can be left child of ' temp . data ' or not ; Create NodeDetails for newNode and add it to the queue ; check whether there are more elements in the arr [ ] and arr [ i ] can be right child of ' temp . data ' or not ; Create NodeDetails for newNode and add it to the queue ; given array represents level order traversal of BST ; given array do not represent level order traversal of BST ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct NodeDetails { int data ; int min , max ; } ; bool levelOrderIsOfBST ( int arr [ ] , int n ) { if ( n == 0 ) return true ; queue < NodeDetails > q ; int i = 0 ; NodeDetails newNode ; newNode . data = arr [ i ++ ] ; newNode . min = INT_MIN ; newNode . max = INT_MAX ; q . push ( newNode ) ; while ( i != n && ! q . empty ( ) ) { NodeDetails temp = q . front ( ) ; q . pop ( ) ; if ( i < n && ( arr [ i ] < temp . data && arr [ i ] > temp . min ) ) { newNode . data = arr [ i ++ ] ; newNode . min = temp . min ; newNode . max = temp . data ; q . push ( newNode ) ; } if ( i < n && ( arr [ i ] > temp . data && arr [ i ] < temp . max ) ) { newNode . data = arr [ i ++ ] ; newNode . min = temp . data ; newNode . max = temp . max ; q . push ( newNode ) ; } } if ( i == n ) return true ; return false ; } int main ( ) { int arr [ ] = { 7 , 4 , 12 , 3 , 6 , 8 , 1 , 5 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( levelOrderIsOfBST ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Construct Tree from given Inorder and Preorder traversals | C ++ program to construct tree using inorder and preorder traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Prototypes for utility functions ; Recursive function to construct binary of size len from Inorder traversal in [ ] and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and len - 1. The function doesn 't do any error checking for cases where inorder and preorder do not form a tree ; Pick current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of value in arr [ start ... end ] The function assumes that value is present in in [ ] ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; This funtcion is here just to test buildTree ( ) ; first recur on left child ; then print the data of node ; now recur on right child ; Driver code ; Let us test the built tree by printing Insorder traversal | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : char data ; node * left ; node * right ; } ; int search ( char arr [ ] , int strt , int end , char value ) ; node * newNode ( char data ) ; node * buildTree ( char in [ ] , char pre [ ] , int inStrt , int inEnd ) { static int preIndex = 0 ; if ( inStrt > inEnd ) return NULL ; node * tNode = newNode ( pre [ preIndex ++ ] ) ; if ( inStrt == inEnd ) return tNode ; int inIndex = search ( in , inStrt , inEnd , tNode -> data ) ; tNode -> left = buildTree ( in , pre , inStrt , inIndex - 1 ) ; tNode -> right = buildTree ( in , pre , inIndex + 1 , inEnd ) ; return tNode ; } int search ( char arr [ ] , int strt , int end , char value ) { int i ; for ( i = strt ; i <= end ; i ++ ) { if ( arr [ i ] == value ) return i ; } } node * newNode ( char data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } void printInorder ( node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> data << " β " ; printInorder ( node -> right ) ; } int main ( ) { char in [ ] = { ' D ' , ' B ' , ' E ' , ' A ' , ' F ' , ' C ' } ; char pre [ ] = { ' A ' , ' B ' , ' D ' , ' E ' , ' C ' , ' F ' } ; int len = sizeof ( in ) / sizeof ( in [ 0 ] ) ; node * root = buildTree ( in , pre , 0 , len - 1 ) ; cout << " Inorder β traversal β of β the β constructed β tree β is β STRNEWLINE " ; printInorder ( root ) ; } |
Lowest Common Ancestor in a Binary Search Tree . | A recursive CPP program to find LCA of two nodes n1 and n2 . ; Function to find LCA of n1 and n2 . The function assumes that both n1 and n2 are present in BST ; If both n1 and n2 are smaller than root , then LCA lies in left ; If both n1 and n2 are greater than root , then LCA lies in right ; Helper function that allocates a new node with the given data . ; Driver code ; Let us construct the BST shown in the above figure | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left , * right ; } ; struct node * lca ( struct node * root , int n1 , int n2 ) { while ( root != NULL ) { if ( root -> data > n1 && root -> data > n2 ) root = root -> left ; else if ( root -> data < n1 && root -> data < n2 ) root = root -> right ; else break ; } return root ; } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = Node -> right = NULL ; return ( Node ) ; } int main ( ) { node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 22 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; int n1 = 10 , n2 = 14 ; node * t = lca ( root , n1 , n2 ) ; cout << " LCA β of β " << n1 << " β and β " << n2 << " β is β " << t -> data << endl ; n1 = 14 , n2 = 8 ; t = lca ( root , n1 , n2 ) ; cout << " LCA β of β " << n1 << " β and β " << n2 << " β is β " << t -> data << endl ; n1 = 10 , n2 = 22 ; t = lca ( root , n1 , n2 ) ; cout << " LCA β of β " << n1 << " β and β " << n2 << " β is β " << t -> data << endl ; return 0 ; } |
A program to check if a binary tree is BST or not | ; false if left is > than node ; false if right is < than node ; false if , recursively , the left or right is not a BST ; passing all that , it 's a BST | int isBST ( struct node * node ) { if ( node == NULL ) return 1 ; if ( node -> left != NULL && node -> left -> data > node -> data ) return 0 ; if ( node -> right != NULL && node -> right -> data < node -> data ) return 0 ; if ( ! isBST ( node -> left ) || ! isBST ( node -> right ) ) return 0 ; return 1 ; } |
A program to check if a binary tree is BST or not | Returns true if a binary tree is a binary search tree ; false if the max of the left is > than us ; false if the min of the right is <= than us ; false if , recursively , the left or right is not a BST ; passing all that , it 's a BST | int isBST ( struct node * node ) { if ( node == NULL ) return 1 ; if ( node -> left != NULL && maxValue ( node -> left ) > node -> data ) return 0 ; if ( node -> right != NULL && minValue ( node -> right ) < node -> data ) return 0 ; if ( ! isBST ( node -> left ) || ! isBST ( node -> right ) ) return 0 ; return 1 ; } |
A program to check if a binary tree is BST or not | C ++ program to check if a given tree is BST . ; A binary tree node has data , pointer to left child and a pointer to right child ; Returns true if given tree is BST . ; Base condition ; if left node exist then check it has correct data or not i . e . left node ' s β data β β should β be β less β than β root ' s data ; if right node exist then check it has correct data or not i . e . right node ' s β data β β should β be β greater β than β root ' s data ; check recursively for every node . ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; bool isBST ( Node * root , Node * l = NULL , Node * r = NULL ) { if ( root == NULL ) return true ; if ( l != NULL and root -> data <= l -> data ) return false ; if ( r != NULL and root -> data >= r -> data ) return false ; return isBST ( root -> left , l , root ) and isBST ( root -> right , root , r ) ; } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( ) { struct Node * root = newNode ( 3 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; if ( isBST ( root , NULL , NULL ) ) cout << " Is β BST " ; else cout << " Not β a β BST " ; return 0 ; } |
A program to check if a binary tree is BST or not | C ++ program to check if a given tree is BST . ; A binary tree node has data , pointer to left child and a pointer to right child ; traverse the tree in inorder fashion and keep track of prev node ; Allows only distinct valued nodes ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; Node ( int data ) { this -> data = data ; left = right = NULL ; } } ; bool isBSTUtil ( struct Node * root , Node * & prev ) { if ( root ) { if ( ! isBSTUtil ( root -> left , prev ) ) return false ; if ( prev != NULL && root -> data <= prev -> data ) return false ; prev = root ; return isBSTUtil ( root -> right , prev ) ; } return true ; } bool isBST ( Node * root ) { Node * prev = NULL ; return isBSTUtil ( root , prev ) ; } int main ( ) { struct Node * root = new Node ( 3 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 5 ) ; root -> left -> left = new Node ( 1 ) ; root -> left -> right = new Node ( 4 ) ; if ( isBST ( root ) ) cout << " Is β BST " ; else cout << " Not β a β BST " ; return 0 ; } |
Find k | A simple inorder traversal based C ++ program to find k - th smallest element in a BST . ; A BST node ; Recursive function to insert an key into BST ; Function to find k 'th largest element in BST Here count denotes the number of nodes processed so far ; base case ; search in left subtree ; if k 'th smallest is found in left subtree, return it ; if current element is k 'th smallest, return it ; else search in right subtree ; Function to find k 'th largest element in BST ; maintain index to count number of nodes processed so far ; main function | #include <iostream> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; Node ( int x ) { data = x ; left = right = NULL ; } } ; Node * insert ( Node * root , int x ) { if ( root == NULL ) return new Node ( x ) ; if ( x < root -> data ) root -> left = insert ( root -> left , x ) ; else if ( x > root -> data ) root -> right = insert ( root -> right , x ) ; return root ; } Node * kthSmallest ( Node * root , int & k ) { if ( root == NULL ) return NULL ; Node * left = kthSmallest ( root -> left , k ) ; if ( left != NULL ) return left ; k -- ; if ( k == 0 ) return root ; return kthSmallest ( root -> right , k ) ; } void printKthSmallest ( Node * root , int k ) { int count = 0 ; Node * res = kthSmallest ( root , k ) ; if ( res == NULL ) cout << " There β are β less β than β k β nodes β in β the β BST " ; else cout << " K - th β Smallest β Element β is β " << res -> data ; } int main ( ) { Node * root = NULL ; int keys [ ] = { 20 , 8 , 22 , 4 , 12 , 10 , 14 } ; for ( int x : keys ) root = insert ( root , x ) ; int k = 3 ; printKthSmallest ( root , k ) ; return 0 ; } |
Find k | A simple inorder traversal based C ++ program to find k - th smallest element in a BST . ; A BST node ; Recursive function to insert an key into BST ; If a node is inserted in left subtree , then lCount of this node is increased . For simplicity , we are assuming that all keys ( tried to be inserted ) are distinct . ; Function to find k 'th largest element in BST Here count denotes the number of nodes processed so far ; base case ; else search in right subtree ; main function | #include <iostream> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; int lCount ; Node ( int x ) { data = x ; left = right = NULL ; lCount = 0 ; } } ; Node * insert ( Node * root , int x ) { if ( root == NULL ) return new Node ( x ) ; if ( x < root -> data ) { root -> left = insert ( root -> left , x ) ; root -> lCount ++ ; } else if ( x > root -> data ) root -> right = insert ( root -> right , x ) ; return root ; } Node * kthSmallest ( Node * root , int k ) { if ( root == NULL ) return NULL ; int count = root -> lCount + 1 ; if ( count == k ) return root ; if ( count > k ) return kthSmallest ( root -> left , k ) ; return kthSmallest ( root -> right , k - count ) ; } int main ( ) { Node * root = NULL ; int keys [ ] = { 20 , 8 , 22 , 4 , 12 , 10 , 14 } ; for ( int x : keys ) root = insert ( root , x ) ; int k = 4 ; Node * res = kthSmallest ( root , k ) ; if ( res == NULL ) cout << " There β are β less β than β k β nodes β in β the β BST " ; else cout << " K - th β Smallest β Element β is β " << res -> data ; return 0 ; } |
Construct Tree from given Inorder and Preorder traversals | C ++ program to construct tree using inorder and preorder traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Recursive function to construct binary of size len from Inorder traversal in [ ] and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and len - 1. The function doesn 't do any error checking for cases where inorder and preorder do not form a tree ; Pick current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; This function mainly creates an unordered_map , then calls buildTree ( ) ; This funtcion is here just to test buildTree ( ) ; Driver program to test above functions ; Let us test the built tree by printing Insorder traversal | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { char data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( char data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } struct Node * buildTree ( char in [ ] , char pre [ ] , int inStrt , int inEnd , unordered_map < char , int > & mp ) { static int preIndex = 0 ; if ( inStrt > inEnd ) return NULL ; char curr = pre [ preIndex ++ ] ; struct Node * tNode = newNode ( curr ) ; if ( inStrt == inEnd ) return tNode ; int inIndex = mp [ curr ] ; tNode -> left = buildTree ( in , pre , inStrt , inIndex - 1 , mp ) ; tNode -> right = buildTree ( in , pre , inIndex + 1 , inEnd , mp ) ; return tNode ; } struct Node * buldTreeWrap ( char in [ ] , char pre [ ] , int len ) { unordered_map < char , int > mp ; for ( int i = 0 ; i < len ; i ++ ) mp [ in [ i ] ] = i ; return buildTree ( in , pre , 0 , len - 1 , mp ) ; } void printInorder ( struct Node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % c β " , node -> data ) ; printInorder ( node -> right ) ; } int main ( ) { char in [ ] = { ' D ' , ' B ' , ' E ' , ' A ' , ' F ' , ' C ' } ; char pre [ ] = { ' A ' , ' B ' , ' D ' , ' E ' , ' C ' , ' F ' } ; int len = sizeof ( in ) / sizeof ( in [ 0 ] ) ; struct Node * root = buldTreeWrap ( in , pre , len ) ; printf ( " Inorder β traversal β of β the β constructed β tree β is β STRNEWLINE " ) ; printInorder ( root ) ; } |
K 'th smallest element in BST using O(1) Extra Space | C ++ program to find k 'th largest element in BST ; A BST node ; A function to find ; Count to iterate over elements till we get the kth smallest number ; store the Kth smallest ; to store the current node ; Like Morris traversal if current does not have left child rather than printing as we did in inorder , we will just increment the count as the number will be in an increasing order ; if count is equal to K then we found the kth smallest , so store it in ksmall ; go to current 's right child ; we create links to Inorder Successor and count using these links ; building links ; link made to Inorder Successor ; While breaking the links in so made temporary threaded tree we will check for the K smallest condition ; Revert the changes made in if part ( break link from the Inorder Successor ) ; If count is equal to K then we found the kth smallest and so store it in ksmall ; return the found value ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Driver Program to test above functions ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; int KSmallestUsingMorris ( Node * root , int k ) { int count = 0 ; int ksmall = INT_MIN ; Node * curr = root ; while ( curr != NULL ) { if ( curr -> left == NULL ) { count ++ ; if ( count == k ) ksmall = curr -> key ; curr = curr -> right ; } else { Node * pre = curr -> left ; while ( pre -> right != NULL && pre -> right != curr ) pre = pre -> right ; if ( pre -> right == NULL ) { pre -> right = curr ; curr = curr -> left ; } else { pre -> right = NULL ; count ++ ; if ( count == k ) ksmall = curr -> key ; curr = curr -> right ; } } } return ksmall ; } Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else if ( key > node -> key ) node -> right = insert ( node -> right , key ) ; return node ; } int main ( ) { Node * root = NULL ; root = insert ( root , 50 ) ; insert ( root , 30 ) ; insert ( root , 20 ) ; insert ( root , 40 ) ; insert ( root , 70 ) ; insert ( root , 60 ) ; insert ( root , 80 ) ; for ( int k = 1 ; k <= 7 ; k ++ ) cout << KSmallestUsingMorris ( root , k ) << " β " ; return 0 ; } |
Check if given sorted sub | C ++ program to find if given array exists as a subsequece in BST ; A binary Tree node ; A utility function to create a new BST node with key as given num ; A utility function to insert a given key to BST ; function to check if given sorted sub - sequence exist in BST index -- > iterator for given sorted sub - sequence seq [ ] -- > given sorted sub - sequence ; We traverse left subtree first in Inorder ; If current node matches with se [ index ] then move forward in sub - sequence ; We traverse left subtree in the end in Inorder ; A wrapper over seqExistUtil . It returns true if seq [ 0. . n - 1 ] exists in tree . ; Initialize index in seq [ ] ; Do an inorder traversal and find if all elements of seq [ ] were present ; index would become n if all elements of seq [ ] were present ; driver program to run the case | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int num ) { struct Node * temp = new Node ; temp -> data = num ; temp -> left = temp -> right = NULL ; return temp ; } struct Node * insert ( struct Node * root , int key ) { if ( root == NULL ) return newNode ( key ) ; if ( root -> data > key ) root -> left = insert ( root -> left , key ) ; else root -> right = insert ( root -> right , key ) ; return root ; } void seqExistUtil ( struct Node * ptr , int seq [ ] , int & index ) { if ( ptr == NULL ) return ; seqExistUtil ( ptr -> left , seq , index ) ; if ( ptr -> data == seq [ index ] ) index ++ ; seqExistUtil ( ptr -> right , seq , index ) ; } bool seqExist ( struct Node * root , int seq [ ] , int n ) { int index = 0 ; seqExistUtil ( root , seq , index ) ; return ( index == n ) ; } int main ( ) { struct Node * root = NULL ; root = insert ( root , 8 ) ; root = insert ( root , 10 ) ; root = insert ( root , 3 ) ; root = insert ( root , 6 ) ; root = insert ( root , 1 ) ; root = insert ( root , 4 ) ; root = insert ( root , 7 ) ; root = insert ( root , 14 ) ; root = insert ( root , 13 ) ; int seq [ ] = { 4 , 6 , 8 , 14 } ; int n = sizeof ( seq ) / sizeof ( seq [ 0 ] ) ; seqExist ( root , seq , n ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Check if an array represents Inorder of Binary Search tree or not | C ++ program to check if a given array is sorted or not . ; Function that returns true if array is Inorder traversal of any Binary Search Tree or not . ; Array has one or no element ; Unsorted pair found ; No unsorted pair found ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isInorder ( int arr [ ] , int n ) { if ( n == 0 n == 1 ) return true ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i - 1 ] > arr [ i ] ) return false ; return true ; } int main ( ) { int arr [ ] = { 19 , 23 , 25 , 30 , 45 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( isInorder ( arr , n ) ) cout << " Yesn " ; else cout << " Non " ; return 0 ; } |
Construct Tree from given Inorder and Preorder traversals | C ++ program to construct a tree using inorder and preorder traversal ; Function to build tree using given traversal ; Function to print tree in Inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; class TreeNode { public : int val ; TreeNode * left ; TreeNode * right ; TreeNode ( int x ) { val = x ; } } ; set < TreeNode * > s ; stack < TreeNode * > st ; TreeNode * buildTree ( int preorder [ ] , int inorder [ ] , int n ) { TreeNode * root = NULL ; for ( int pre = 0 , in = 0 ; pre < n ; ) { TreeNode * node = NULL ; do { node = new TreeNode ( preorder [ pre ] ) ; if ( root == NULL ) { root = node ; } if ( st . size ( ) > 0 ) { if ( s . find ( st . top ( ) ) != s . end ( ) ) { s . erase ( st . top ( ) ) ; st . top ( ) -> right = node ; st . pop ( ) ; } else { st . top ( ) -> left = node ; } } st . push ( node ) ; } while ( preorder [ pre ++ ] != inorder [ in ] && pre < n ) ; node = NULL ; while ( st . size ( ) > 0 && in < n && st . top ( ) -> val == inorder [ in ] ) { node = st . top ( ) ; st . pop ( ) ; in ++ ; } if ( node != NULL ) { s . insert ( node ) ; st . push ( node ) ; } } return root ; } void printInorder ( TreeNode * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> val << " β " ; printInorder ( node -> right ) ; } int main ( ) { int in [ ] = { 9 , 8 , 4 , 2 , 10 , 5 , 10 , 1 , 6 , 3 , 13 , 12 , 7 } ; int pre [ ] = { 1 , 2 , 4 , 8 , 9 , 5 , 10 , 10 , 3 , 6 , 7 , 12 , 13 } ; int len = sizeof ( in ) / sizeof ( int ) ; TreeNode * root = buildTree ( pre , in , len ) ; printInorder ( root ) ; return 0 ; } |
Check if two BSTs contain same set of elements | CPP program to check if two BSTs contains same set of elements ; BST Node ; Utility function to create new Node ; function to insert elements of the tree to map m ; function to check if the two BSTs contain same set of elements ; Base cases ; Create two hash sets and store elements both BSTs in them . ; Return true if both hash sets contain same elements . ; Driver program to check above functions ; First BST ; Second BST ; check if two BSTs have same set of elements | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; Node * newNode ( int val ) { Node * temp = new Node ; temp -> data = val ; temp -> left = temp -> right = NULL ; return temp ; } void insertToHash ( Node * root , unordered_set < int > & s ) { if ( ! root ) return ; insertToHash ( root -> left , s ) ; s . insert ( root -> data ) ; insertToHash ( root -> right , s ) ; } bool checkBSTs ( Node * root1 , Node * root2 ) { if ( ! root1 && ! root2 ) return true ; if ( ( root1 && ! root2 ) || ( ! root1 && root2 ) ) return false ; unordered_set < int > s1 , s2 ; insertToHash ( root1 , s1 ) ; insertToHash ( root2 , s2 ) ; return ( s1 == s2 ) ; } int main ( ) { Node * root1 = newNode ( 15 ) ; root1 -> left = newNode ( 10 ) ; root1 -> right = newNode ( 20 ) ; root1 -> left -> left = newNode ( 5 ) ; root1 -> left -> right = newNode ( 12 ) ; root1 -> right -> right = newNode ( 25 ) ; Node * root2 = newNode ( 15 ) ; root2 -> left = newNode ( 12 ) ; root2 -> right = newNode ( 20 ) ; root2 -> left -> left = newNode ( 5 ) ; root2 -> left -> left -> right = newNode ( 10 ) ; root2 -> right -> right = newNode ( 25 ) ; if ( checkBSTs ( root1 , root2 ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Check if two BSTs contain same set of elements | CPP program to check if two BSTs contains same set of elements ; BST Node ; Utility function to create new Node ; function to insert elements of the tree to map m ; function to check if the two BSTs contain same set of elements ; Base cases ; Create two vectors and store inorder traversals of both BSTs in them . ; Return true if both vectors are identical ; Driver program to check above functions ; First BST ; Second BST ; check if two BSTs have same set of elements | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; Node * newNode ( int val ) { Node * temp = new Node ; temp -> data = val ; temp -> left = temp -> right = NULL ; return temp ; } void storeInorder ( Node * root , vector < int > & v ) { if ( ! root ) return ; storeInorder ( root -> left , v ) ; v . push_back ( root -> data ) ; storeInorder ( root -> right , v ) ; } bool checkBSTs ( Node * root1 , Node * root2 ) { if ( ! root1 && ! root2 ) return true ; if ( ( root1 && ! root2 ) || ( ! root1 && root2 ) ) return false ; vector < int > v1 , v2 ; storeInorder ( root1 , v1 ) ; storeInorder ( root2 , v2 ) ; return ( v1 == v2 ) ; } int main ( ) { Node * root1 = newNode ( 15 ) ; root1 -> left = newNode ( 10 ) ; root1 -> right = newNode ( 20 ) ; root1 -> left -> left = newNode ( 5 ) ; root1 -> left -> right = newNode ( 12 ) ; root1 -> right -> right = newNode ( 25 ) ; Node * root2 = newNode ( 15 ) ; root2 -> left = newNode ( 12 ) ; root2 -> right = newNode ( 20 ) ; root2 -> left -> left = newNode ( 5 ) ; root2 -> left -> left -> right = newNode ( 10 ) ; root2 -> right -> right = newNode ( 25 ) ; if ( checkBSTs ( root1 , root2 ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Shortest distance between two nodes in BST | CPP program to find distance between two nodes in BST ; Standard BST insert function ; This function returns distance of x from root . This function assumes that x exists in BST and BST is not NULL . ; Returns minimum distance between a and b . This function assumes that a and b exist in BST . ; Both keys lie in left ; Both keys lie in right same path ; Lie in opposite directions ( Root is LCA of two nodes ) ; This function make sure that a is smaller than b before making a call to findDistWrapper ( ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { struct Node * left , * right ; int key ; } ; struct Node * newNode ( int key ) { struct Node * ptr = new Node ; ptr -> key = key ; ptr -> left = ptr -> right = NULL ; return ptr ; } struct Node * insert ( struct Node * root , int key ) { if ( ! root ) root = newNode ( key ) ; else if ( root -> key > key ) root -> left = insert ( root -> left , key ) ; else if ( root -> key < key ) root -> right = insert ( root -> right , key ) ; return root ; } int distanceFromRoot ( struct Node * root , int x ) { if ( root -> key == x ) return 0 ; else if ( root -> key > x ) return 1 + distanceFromRoot ( root -> left , x ) ; return 1 + distanceFromRoot ( root -> right , x ) ; } int distanceBetween2 ( struct Node * root , int a , int b ) { if ( ! root ) return 0 ; if ( root -> key > a && root -> key > b ) return distanceBetween2 ( root -> left , a , b ) ; if ( root -> key < a && root -> key < b ) return distanceBetween2 ( root -> right , a , b ) ; if ( root -> key >= a && root -> key <= b ) return distanceFromRoot ( root , a ) + distanceFromRoot ( root , b ) ; } int findDistWrapper ( Node * root , int a , int b ) { if ( a > b ) swap ( a , b ) ; return distanceBetween2 ( root , a , b ) ; } int main ( ) { struct Node * root = NULL ; root = insert ( root , 20 ) ; insert ( root , 10 ) ; insert ( root , 5 ) ; insert ( root , 15 ) ; insert ( root , 30 ) ; insert ( root , 25 ) ; insert ( root , 35 ) ; int a = 5 , b = 55 ; cout << findDistWrapper ( root , 5 , 35 ) ; return 0 ; } |
Print BST keys in given Range | O ( 1 ) Space | CPP code to print BST keys in given Range in constant space using Morris traversal . ; Function to print the keys in range ; check if current node lies between n1 and n2 ; finding the inorder predecessor - inorder predecessor is the right most in left subtree or the left child , i . e in BST it is the maximum ( right most ) in left subtree . ; check if current node lies between n1 and n2 ; Helper function to create a new node ; Driver Code ; Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; void RangeTraversal ( node * root , int n1 , int n2 ) { if ( ! root ) return ; node * curr = root ; while ( curr ) { if ( curr -> left == NULL ) { if ( curr -> data <= n2 && curr -> data >= n1 ) { cout << curr -> data << " β " ; } curr = curr -> right ; } else { node * pre = curr -> left ; while ( pre -> right != NULL && pre -> right != curr ) pre = pre -> right ; if ( pre -> right == NULL ) { pre -> right = curr ; curr = curr -> left ; } else { pre -> right = NULL ; if ( curr -> data <= n2 && curr -> data >= n1 ) { cout << curr -> data << " β " ; } curr = curr -> right ; } } } } node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> right = temp -> left = NULL ; return temp ; } int main ( ) { node * root = newNode ( 4 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 7 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 10 ) ; RangeTraversal ( root , 4 , 12 ) ; return 0 ; } |
Count BST subtrees that lie in given range | C ++ program to count subtrees that lie in a given range ; A BST node ; A utility function to check if data of root is in range from low to high ; A recursive function to get count of nodes whose subtree is in range from low to hgih . This function returns true if nodes in subtree rooted under ' root ' are in range . ; Base case ; Recur for left and right subtrees ; If both left and right subtrees are in range and current node is also in range , then increment count and return true ; A wrapper over getCountUtil ( ) . This function initializes count as 0 and calls getCountUtil ( ) ; Utility function to create new node ; Driver program ; Let us construct the BST shown in the above figure ; Let us constructed BST shown in above example 10 / \ 5 50 / / \ 1 40 100 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; bool inRange ( node * root , int low , int high ) { return root -> data >= low && root -> data <= high ; } bool getCountUtil ( node * root , int low , int high , int * count ) { if ( root == NULL ) return true ; bool l = getCountUtil ( root -> left , low , high , count ) ; bool r = getCountUtil ( root -> right , low , high , count ) ; if ( l && r && inRange ( root , low , high ) ) { ++ * count ; return true ; } return false ; } int getCount ( node * root , int low , int high ) { int count = 0 ; getCountUtil ( root , low , high , & count ) ; return count ; } node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int main ( ) { node * root = newNode ( 10 ) ; root -> left = newNode ( 5 ) ; root -> right = newNode ( 50 ) ; root -> left -> left = newNode ( 1 ) ; root -> right -> left = newNode ( 40 ) ; root -> right -> right = newNode ( 100 ) ; int l = 5 ; int h = 45 ; cout << " Count β of β subtrees β in β [ " << l << " , β " << h << " ] β is β " << getCount ( root , l , h ) ; return 0 ; } |
Remove all leaf nodes from the binary search tree | C ++ program to delete leaf Node from binary search tree . ; Create a newNode in binary search tree . ; Insert a Node in binary search tree . ; Function for inorder traversal in a BST . ; Delete leaf nodes from binary search tree . ; Else recursively delete in left and right subtrees . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } struct Node * insert ( struct Node * root , int data ) { if ( root == NULL ) return newNode ( data ) ; if ( data < root -> data ) root -> left = insert ( root -> left , data ) ; else if ( data > root -> data ) root -> right = insert ( root -> right , data ) ; return root ; } void inorder ( struct Node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; cout << root -> data << " β " ; inorder ( root -> right ) ; } } struct Node * leafDelete ( struct Node * root ) { if ( root == NULL ) return NULL ; if ( root -> left == NULL && root -> right == NULL ) { free ( root ) ; return NULL ; } root -> left = leafDelete ( root -> left ) ; root -> right = leafDelete ( root -> right ) ; return root ; } int main ( ) { struct Node * root = NULL ; root = insert ( root , 20 ) ; insert ( root , 10 ) ; insert ( root , 5 ) ; insert ( root , 15 ) ; insert ( root , 30 ) ; insert ( root , 25 ) ; insert ( root , 35 ) ; cout << " Inorder β before β Deleting β the β leaf β Node . " << endl ; inorder ( root ) ; cout << endl ; leafDelete ( root ) ; cout << " INorder β after β Deleting β the β leaf β Node . " << endl ; inorder ( root ) ; return 0 ; } |
Sum of k smallest elements in BST | c ++ program to find Sum Of All Elements smaller than or equal to Kth Smallest Element In BST ; Binary tree Node ; utility function new Node of BST ; A utility function to insert a new Node with given key in BST and also maintain lcount , Sum ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; return the ( unchanged ) Node pointer ; function return sum of all element smaller than and equal to Kth smallest element ; Base cases ; Compute sum of elements in left subtree ; Add root 's data ; Add current Node ; If count is less than k , return right subtree Nodes ; Wrapper over ksmallestElementSumRec ( ) ; Driver program to test above functions ; 20 / \ 8 22 / \ 4 12 / \ 10 14 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; struct Node * createNode ( int data ) { Node * new_Node = new Node ; new_Node -> left = NULL ; new_Node -> right = NULL ; new_Node -> data = data ; return new_Node ; } struct Node * insert ( Node * root , int key ) { if ( root == NULL ) return createNode ( key ) ; if ( root -> data > key ) root -> left = insert ( root -> left , key ) ; else if ( root -> data < key ) root -> right = insert ( root -> right , key ) ; return root ; } int ksmallestElementSumRec ( Node * root , int k , int & count ) { if ( root == NULL ) return 0 ; if ( count > k ) return 0 ; int res = ksmallestElementSumRec ( root -> left , k , count ) ; if ( count >= k ) return res ; res += root -> data ; count ++ ; if ( count >= k ) return res ; return res + ksmallestElementSumRec ( root -> right , k , count ) ; } int ksmallestElementSum ( struct Node * root , int k ) { int count = 0 ; ksmallestElementSumRec ( root , k , count ) ; } int main ( ) { Node * root = NULL ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 4 ) ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 14 ) ; root = insert ( root , 22 ) ; int k = 3 ; cout << ksmallestElementSum ( root , k ) << endl ; return 0 ; } |
Sum of k smallest elements in BST | C ++ program to find Sum Of All Elements smaller than or equal t Kth Smallest Element In BST ; Binary tree Node ; utility function new Node of BST ; A utility function to insert a new Node with given key in BST and also maintain lcount , Sum ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; increment lCount of current Node ; increment current Node sum by adding key into it ; return the ( unchanged ) Node pointer ; function return sum of all element smaller than and equal to Kth smallest element ; if we fount k smallest element then break the function ; store sum of all element smaller than current root ; ; decremented k and call right sub - tree ; call left sub - tree ; Wrapper over ksmallestElementSumRec ( ) ; Driver program to test above functions ; 20 / \ 8 22 / \ 4 12 / \ 10 14 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; int lCount ; int Sum ; Node * left ; Node * right ; } ; struct Node * createNode ( int data ) { Node * new_Node = new Node ; new_Node -> left = NULL ; new_Node -> right = NULL ; new_Node -> data = data ; new_Node -> lCount = 0 ; new_Node -> Sum = 0 ; return new_Node ; } struct Node * insert ( Node * root , int key ) { if ( root == NULL ) return createNode ( key ) ; if ( root -> data > key ) { root -> lCount ++ ; root -> Sum += key ; root -> left = insert ( root -> left , key ) ; } else if ( root -> data < key ) root -> right = insert ( root -> right , key ) ; return root ; } void ksmallestElementSumRec ( Node * root , int k , int & temp_sum ) { if ( root == NULL ) return ; if ( ( root -> lCount + 1 ) == k ) { temp_sum += root -> data + root -> Sum ; return ; } else if ( k > root -> lCount ) { temp_sum += root -> data + root -> Sum ; k = k - ( root -> lCount + 1 ) ; ksmallestElementSumRec ( root -> right , k , temp_sum ) ; } else ksmallestElementSumRec ( root -> left , k , temp_sum ) ; } int ksmallestElementSum ( struct Node * root , int k ) { int sum = 0 ; ksmallestElementSumRec ( root , k , sum ) ; return sum ; } int main ( ) { Node * root = NULL ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 4 ) ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 14 ) ; root = insert ( root , 22 ) ; int k = 3 ; cout << ksmallestElementSum ( root , k ) << endl ; return 0 ; } |
Inorder predecessor and successor for a given key in BST | | struct Node { int key ; struct Node * left , * right ; } ; |
Inorder predecessor and successor for a given key in BST | CPP code for inorder successor and predecessor of tree ; Function to return data ; since inorder traversal results in ascending order visit to node , we can store the values of the largest no which is smaller than a ( predecessor ) and smallest no which is large than a ( successor ) using inorder traversal ; If root is null return ; traverse the left subtree ; root data is greater than a ; q stores the node whose data is greater than a and is smaller than the previously stored data in * q which is successor ; if the root data is smaller than store it in p which is predecessor ; traverse the right subtree ; Driver code | #include <iostream> NEW_LINE #include <stdlib.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * getnode ( int info ) { Node * p = ( Node * ) malloc ( sizeof ( Node ) ) ; p -> data = info ; p -> right = NULL ; p -> left = NULL ; return p ; } void find_p_s ( Node * root , int a , Node * * p , Node * * q ) { if ( ! root ) return ; find_p_s ( root -> left , a , p , q ) ; if ( root && root -> data > a ) { if ( ( ! * q ) || ( * q ) && ( * q ) -> data > root -> data ) * q = root ; } else if ( root && root -> data < a ) { * p = root ; } find_p_s ( root -> right , a , p , q ) ; } int main ( ) { Node * root1 = getnode ( 50 ) ; root1 -> left = getnode ( 20 ) ; root1 -> right = getnode ( 60 ) ; root1 -> left -> left = getnode ( 10 ) ; root1 -> left -> right = getnode ( 30 ) ; root1 -> right -> left = getnode ( 55 ) ; root1 -> right -> right = getnode ( 70 ) ; Node * p = NULL , * q = NULL ; find_p_s ( root1 , 55 , & p , & q ) ; if ( p ) cout << p -> data ; if ( q ) cout << " β " << q -> data ; return 0 ; } |
Inorder predecessor and successor for a given key in BST | Iterative Approach | C ++ program to find predecessor and successor in a BST ; BST Node ; Function that finds predecessor and successor of key in BST . ; Search for given key in BST . ; If root is given key . ; the minimum value in right subtree is predecessor . ; the maximum value in left subtree is successor . ; If key is greater than root , then key lies in right subtree . Root could be predecessor if left subtree of key is null . ; If key is smaller than root , then key lies in left subtree . Root could be successor if right subtree of key is null . ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; Driver program to test above function ; Key to be searched in BST ; Let us create following BST 50 / \ / \ 30 70 / \ / \ / \ / \ 20 40 60 80 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; void findPreSuc ( Node * root , Node * & pre , Node * & suc , int key ) { if ( root == NULL ) return ; while ( root != NULL ) { if ( root -> key == key ) { if ( root -> right ) { suc = root -> right ; while ( suc -> left ) suc = suc -> left ; } if ( root -> left ) { pre = root -> left ; while ( pre -> right ) pre = pre -> right ; } return ; } else if ( root -> key < key ) { pre = root ; root = root -> right ; } else { suc = root ; root = root -> left ; } } } Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else node -> right = insert ( node -> right , key ) ; return node ; } int main ( ) { int key = 65 ; Node * root = NULL ; root = insert ( root , 50 ) ; insert ( root , 30 ) ; insert ( root , 20 ) ; insert ( root , 40 ) ; insert ( root , 70 ) ; insert ( root , 60 ) ; insert ( root , 80 ) ; Node * pre = NULL , * suc = NULL ; findPreSuc ( root , pre , suc , key ) ; if ( pre != NULL ) cout << " Predecessor β is β " << pre -> key << endl ; else cout << " - 1" ; if ( suc != NULL ) cout << " Successor β is β " << suc -> key ; else cout << " - 1" ; return 0 ; } |
Three numbers in a BST that adds upto zero | A C ++ program to check if there is a triplet with sum equal to 0 in a given BST ; A BST node has key , and left and right pointers ; A function to convert given BST to Doubly Linked List . left pointer is used as previous pointer and right pointer is used as next pointer . The function sets * head to point to first and * tail to point to last node of converted DLL ; Base case ; First convert the left subtree ; Then change left of current root as last node of left subtree ; If tail is not NULL , then set right of tail as root , else current node is head ; Update tail ; Finally , convert right subtree ; This function returns true if there is pair in DLL with sum equal to given sum . The algorithm is similar to hasArrayTwoCandidates ( ) tinyurl . com / dy6palr in method 1 of http : ; The main function that returns true if there is a 0 sum triplet in BST otherwise returns false ; Check if the given BST is empty ; Convert given BST to doubly linked list . head and tail store the pointers to first and last nodes in DLLL ; Now iterate through every node and find if there is a pair with sum equal to - 1 * heaf -> key where head is current node ; If there is a pair with sum equal to - 1 * head -> key , then return true else move forward ; If we reach here , then there was no 0 sum triplet ; A utility function to create a new BST node with key as given num ; A utility function to insert a given key to BST ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int key ; node * left ; node * right ; } ; void convertBSTtoDLL ( node * root , node * * head , node * * tail ) { if ( root == NULL ) return ; if ( root -> left ) convertBSTtoDLL ( root -> left , head , tail ) ; root -> left = * tail ; if ( * tail ) ( * tail ) -> right = root ; else * head = root ; * tail = root ; if ( root -> right ) convertBSTtoDLL ( root -> right , head , tail ) ; } bool isPresentInDLL ( node * head , node * tail , int sum ) { while ( head != tail ) { int curr = head -> key + tail -> key ; if ( curr == sum ) return true ; else if ( curr > sum ) tail = tail -> left ; else head = head -> right ; } return false ; } bool isTripletPresent ( node * root ) { if ( root == NULL ) return false ; node * head = NULL ; node * tail = NULL ; convertBSTtoDLL ( root , & head , & tail ) ; while ( ( head -> right != tail ) && ( head -> key < 0 ) ) { if ( isPresentInDLL ( head -> right , tail , -1 * head -> key ) ) return true ; else head = head -> right ; } return false ; } node * newNode ( int num ) { node * temp = new node ( ) ; temp -> key = num ; temp -> left = temp -> right = NULL ; return temp ; } node * insert ( node * root , int key ) { if ( root == NULL ) return newNode ( key ) ; if ( root -> key > key ) root -> left = insert ( root -> left , key ) ; else root -> right = insert ( root -> right , key ) ; return root ; } int main ( ) { node * root = NULL ; root = insert ( root , 6 ) ; root = insert ( root , -13 ) ; root = insert ( root , 14 ) ; root = insert ( root , -8 ) ; root = insert ( root , 15 ) ; root = insert ( root , 13 ) ; root = insert ( root , 7 ) ; if ( isTripletPresent ( root ) ) cout << " Present " ; else cout << " Not β Present " ; return 0 ; } |
Find a pair with given sum in a Balanced BST | In a balanced binary search tree isPairPresent two element which sums to a given value time O ( n ) space O ( logn ) ; A BST node ; Stack type ; A utility function to create a stack of given size ; BASIC OPERATIONS OF STACK ; Returns true if a pair with target sum exists in BST , otherwise false ; Create two stacks . s1 is used for normal inorder traversal and s2 is used for reverse inorder traversal ; Note the sizes of stacks is MAX_SIZE , we can find the tree size and fix stack size as O ( Logn ) for balanced trees like AVL and Red Black tree . We have used MAX_SIZE to keep the code simple done1 , val1 and curr1 are used for normal inorder traversal using s1 done2 , val2 and curr2 are used for reverse inorder traversal using s2 ; The loop will break when we either find a pair or one of the two traversals is complete ; Find next node in normal Inorder traversal . See following post www . geeksforgeeks . org / inorder - tree - traversal - without - recursion / https : ; Find next node in REVERSE Inorder traversal . The only difference between above and below loop is , in below loop right subtree is traversed before left subtree ; If we find a pair , then print the pair and return . The first condition makes sure that two same values are not added ; If sum of current values is smaller , then move to next node in normal inorder traversal ; If sum of current values is greater , then move to next node in reverse inorder traversal ; If any of the inorder traversals is over , then there is no pair so return false ; A utility function to create BST node ; Driver program to test above functions ; 15 / \ 10 20 / \ / \ 8 12 16 25 | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_SIZE 100 NEW_LINE class node { public : int val ; node * left , * right ; } ; class Stack { public : int size ; int top ; node * * array ; } ; Stack * createStack ( int size ) { Stack * stack = new Stack ( ) ; stack -> size = size ; stack -> top = -1 ; stack -> array = new node * [ ( stack -> size * sizeof ( node * ) ) ] ; return stack ; } int isFull ( Stack * stack ) { return stack -> top - 1 == stack -> size ; } int isEmpty ( Stack * stack ) { return stack -> top == -1 ; } void push ( Stack * stack , node * node ) { if ( isFull ( stack ) ) return ; stack -> array [ ++ stack -> top ] = node ; } node * pop ( Stack * stack ) { if ( isEmpty ( stack ) ) return NULL ; return stack -> array [ stack -> top -- ] ; } bool isPairPresent ( node * root , int target ) { Stack * s1 = createStack ( MAX_SIZE ) ; Stack * s2 = createStack ( MAX_SIZE ) ; bool done1 = false , done2 = false ; int val1 = 0 , val2 = 0 ; node * curr1 = root , * curr2 = root ; while ( 1 ) { while ( done1 == false ) { if ( curr1 != NULL ) { push ( s1 , curr1 ) ; curr1 = curr1 -> left ; } else { if ( isEmpty ( s1 ) ) done1 = 1 ; else { curr1 = pop ( s1 ) ; val1 = curr1 -> val ; curr1 = curr1 -> right ; done1 = 1 ; } } } while ( done2 == false ) { if ( curr2 != NULL ) { push ( s2 , curr2 ) ; curr2 = curr2 -> right ; } else { if ( isEmpty ( s2 ) ) done2 = 1 ; else { curr2 = pop ( s2 ) ; val2 = curr2 -> val ; curr2 = curr2 -> left ; done2 = 1 ; } } } if ( ( val1 != val2 ) && ( val1 + val2 ) == target ) { cout << " Pair β Found : β " << val1 << " + β " << val2 << " β = β " << target << endl ; return true ; } else if ( ( val1 + val2 ) < target ) done1 = false ; else if ( ( val1 + val2 ) > target ) done2 = false ; if ( val1 >= val2 ) return false ; } } node * NewNode ( int val ) { node * tmp = new node ( ) ; tmp -> val = val ; tmp -> right = tmp -> left = NULL ; return tmp ; } int main ( ) { node * root = NewNode ( 15 ) ; root -> left = NewNode ( 10 ) ; root -> right = NewNode ( 20 ) ; root -> left -> left = NewNode ( 8 ) ; root -> left -> right = NewNode ( 12 ) ; root -> right -> left = NewNode ( 16 ) ; root -> right -> right = NewNode ( 25 ) ; int target = 33 ; if ( isPairPresent ( root , target ) == false ) cout << " No such values are found " ; return 0 ; } |
Find a pair with given sum in BST | CPP program to find a pair with given sum using hashing ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * NewNode ( int data ) { Node * temp = ( Node * ) malloc ( sizeof ( Node ) ) ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } Node * insert ( Node * root , int key ) { if ( root == NULL ) return NewNode ( key ) ; if ( key < root -> data ) root -> left = insert ( root -> left , key ) ; else root -> right = insert ( root -> right , key ) ; return root ; } bool findpairUtil ( Node * root , int sum , unordered_set < int > & set ) { if ( root == NULL ) return false ; if ( findpairUtil ( root -> left , sum , set ) ) return true ; if ( set . find ( sum - root -> data ) != set . end ( ) ) { cout << " Pair β is β found β ( " << sum - root -> data << " , β " << root -> data << " ) " << endl ; return true ; } else set . insert ( root -> data ) ; return findpairUtil ( root -> right , sum , set ) ; } void findPair ( Node * root , int sum ) { unordered_set < int > set ; if ( ! findpairUtil ( root , sum , set ) ) cout << " Pairs β do β not β exit " << endl ; } int main ( ) { Node * root = NULL ; root = insert ( root , 15 ) ; root = insert ( root , 10 ) ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 12 ) ; root = insert ( root , 16 ) ; root = insert ( root , 25 ) ; root = insert ( root , 10 ) ; int sum = 33 ; findPair ( root , sum ) ; return 0 ; } |
Find pairs with given sum such that pair elements lie in different BSTs | C ++ program to find pairs with given sum such that one element of pair exists in one BST and other in other BST . ; A binary Tree node ; A utility function to create a new BST node with key as given num ; A utility function to insert a given key to BST ; store storeInorder traversal in auxiliary array ; Function to find pair for given sum in different bst vect1 [ ] -- > stores storeInorder traversal of first bst vect2 [ ] -- > stores storeInorder traversal of second bst ; Initialize two indexes to two different corners of two vectors . ; find pair by moving two corners . ; If we found a pair ; If sum is more , move to higher value in first vector . ; If sum is less , move to lower value in second vector . ; Prints all pairs with given " sum " such that one element of pair is in tree with root1 and other node is in tree with root2 . ; Store inorder traversals of two BSTs in two vectors . ; Now the problem reduces to finding a pair with given sum such that one element is in vect1 and other is in vect2 . ; Driver program to run the case ; first BST ; second BST | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int num ) { struct Node * temp = new Node ; temp -> data = num ; temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * root , int key ) { if ( root == NULL ) return newNode ( key ) ; if ( root -> data > key ) root -> left = insert ( root -> left , key ) ; else root -> right = insert ( root -> right , key ) ; return root ; } void storeInorder ( Node * ptr , vector < int > & vect ) { if ( ptr == NULL ) return ; storeInorder ( ptr -> left , vect ) ; vect . push_back ( ptr -> data ) ; storeInorder ( ptr -> right , vect ) ; } void pairSumUtil ( vector < int > & vect1 , vector < int > & vect2 , int sum ) { int left = 0 ; int right = vect2 . size ( ) - 1 ; while ( left < vect1 . size ( ) && right >= 0 ) { if ( vect1 [ left ] + vect2 [ right ] == sum ) { cout << " ( " << vect1 [ left ] << " , β " << vect2 [ right ] << " ) , β " ; left ++ ; right -- ; } else if ( vect1 [ left ] + vect2 [ right ] < sum ) left ++ ; else right -- ; } } void pairSum ( Node * root1 , Node * root2 , int sum ) { vector < int > vect1 , vect2 ; storeInorder ( root1 , vect1 ) ; storeInorder ( root2 , vect2 ) ; pairSumUtil ( vect1 , vect2 , sum ) ; } int main ( ) { struct Node * root1 = NULL ; root1 = insert ( root1 , 8 ) ; root1 = insert ( root1 , 10 ) ; root1 = insert ( root1 , 3 ) ; root1 = insert ( root1 , 6 ) ; root1 = insert ( root1 , 1 ) ; root1 = insert ( root1 , 5 ) ; root1 = insert ( root1 , 7 ) ; root1 = insert ( root1 , 14 ) ; root1 = insert ( root1 , 13 ) ; struct Node * root2 = NULL ; root2 = insert ( root2 , 5 ) ; root2 = insert ( root2 , 18 ) ; root2 = insert ( root2 , 2 ) ; root2 = insert ( root2 , 1 ) ; root2 = insert ( root2 , 3 ) ; root2 = insert ( root2 , 4 ) ; int sum = 10 ; pairSum ( root1 , root2 , sum ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.