text
stringlengths
25
2.53k
code
stringlengths
46
4.32k
Write a Program to Find the Maximum Depth or Height of a Tree | ; A binary tree node has data , pointer to left child and a pointer to right child ; Compute the " maxDepth " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the depth of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; int maxDepth ( struct node * node ) { if ( node == NULL ) return 0 ; else { int lDepth = maxDepth ( node -> left ) ; int rDepth = maxDepth ( node -> right ) ; if ( lDepth > rDepth ) return ( lDepth + 1 ) ; else return ( rDepth + 1 ) ; } } 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 ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; printf ( " Height ▁ of ▁ tree ▁ is ▁ % d " , maxDepth ( root ) ) ; getchar ( ) ; return 0 ; }
How to determine if a binary tree is height | C program to check if a tree is height - balanced or not ; A binary tree node has data , pointer to left child and a pointer to right child ; Returns the height of a binary tree ; Returns true if binary tree with root as root is height - balanced ; for height of left subtree ; for height of right subtree ; If tree is empty then return true ; Get the height of left and right sub trees ; If we reach here then tree is not height - balanced ; returns maximum of two integers ; The function Compute the " height " of a tree . Height is the number of nodes along the longest path from the root node down to the farthest leaf node . ; base case tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define bool int NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; int height ( struct node * node ) ; bool isBalanced ( struct node * root ) { int lh ; int rh ; if ( root == NULL ) return 1 ; lh = height ( root -> left ) ; rh = height ( root -> right ) ; if ( abs ( lh - rh ) <= 1 && isBalanced ( root -> left ) && isBalanced ( root -> right ) ) return 1 ; return 0 ; } int max ( int a , int b ) { return ( a >= b ) ? a : b ; } int height ( struct node * node ) { if ( node == NULL ) return 0 ; return 1 + max ( height ( node -> left ) , height ( 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 ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> left -> left -> left = newNode ( 8 ) ; if ( isBalanced ( root ) ) printf ( " Tree ▁ is ▁ balanced " ) ; else printf ( " Tree ▁ is ▁ not ▁ balanced " ) ; getchar ( ) ; return 0 ; }
Diameter of a Binary Tree | Recursive optimized C program to find the diameter of a 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 with the given data and NULL left and right pointers . ; returns max of two integers ; The function Compute the " height " of a tree . Height is the number f nodes along the longest path from the root node down to the farthest leaf node . ; base case tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Function to get diameter of a binary tree ; base case where tree is empty ; get the height of left and right sub - trees ; get the diameter of left and right sub - trees ; Return max of following three 1 ) Diameter of left subtree 2 ) Diameter of right subtree 3 ) Height of left subtree + height of right subtree + 1 ; Driver Code ; Constructed binary tree is 1 / \ 2 3 / \ 4 5 ; Function Call
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left , * 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 ) ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } int height ( struct node * node ) { if ( node == NULL ) return 0 ; return 1 + max ( height ( node -> left ) , height ( node -> right ) ) ; } int diameter ( struct node * tree ) { if ( tree == NULL ) return 0 ; int lheight = height ( tree -> left ) ; int rheight = height ( tree -> right ) ; int ldiameter = diameter ( tree -> left ) ; int rdiameter = diameter ( tree -> right ) ; return max ( lheight + rheight + 1 , max ( ldiameter , rdiameter ) ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; printf ( " Diameter ▁ of ▁ the ▁ given ▁ binary ▁ tree ▁ is ▁ % d STRNEWLINE " , diameter ( root ) ) ; return 0 ; }
Find if possible to visit every nodes in given Graph exactly once based on given conditions | C ++ program for above approach . ; Function to find print path ; If a [ 0 ] is 1 ; Printing path ; Seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; Printing path ; If a [ N - 1 ] = 0 ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findpath ( int N , int a [ ] ) { if ( a [ 0 ] ) { printf ( " % d ▁ " , N + 1 ) ; for ( int i = 1 ; i <= N ; i ++ ) printf ( " % d ▁ " , i ) ; return ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( ! a [ i ] && a [ i + 1 ] ) { for ( int j = 1 ; j <= i ; j ++ ) printf ( " % d ▁ " , j ) ; printf ( " % d ▁ " , N + 1 ) ; for ( int j = i + 1 ; j <= N ; j ++ ) printf ( " % d ▁ " , j ) ; return ; } } for ( int i = 1 ; i <= N ; i ++ ) printf ( " % d ▁ " , i ) ; printf ( " % d ▁ " , N + 1 ) ; } int main ( ) { int N = 3 , arr [ ] = { 0 , 1 , 0 } ; findpath ( N , arr ) ; }
Find depth of the deepest odd level leaf node | C program to find depth of the deepest odd level leaf node ; A utility function to find maximum of two integers ; A Binary Tree node ; A utility function to allocate a new tree node ; A recursive function to find depth of the deepest odd level leaf ; Base Case ; If this node is a leaf and its level is odd , return its level ; If not leaf , return the maximum value from left and right subtrees ; Main function which calculates the depth of deepest odd level leaf . This function mainly uses depthOfOddLeafUtil ( ) ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int max ( int x , int y ) { return ( x > y ) ? x : y ; } struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } int depthOfOddLeafUtil ( struct Node * root , int level ) { if ( root == NULL ) return 0 ; if ( root -> left == NULL && root -> right == NULL && level & 1 ) return level ; return max ( depthOfOddLeafUtil ( root -> left , level + 1 ) , depthOfOddLeafUtil ( root -> right , level + 1 ) ) ; } int depthOfOddLeaf ( struct Node * root ) { int level = 1 , depth = 0 ; return depthOfOddLeafUtil ( root , level ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; root -> right -> right -> right -> right = newNode ( 10 ) ; root -> right -> right -> right -> right -> left = newNode ( 11 ) ; printf ( " % d ▁ is ▁ the ▁ required ▁ depth STRNEWLINE " , depthOfOddLeaf ( root ) ) ; getchar ( ) ; return 0 ; }
Reorder an array such that sum of left half is not equal to sum of right half | C program for the above approach ; A comparator function used by qsort ; Function to print the required reordering of array if possible ; Sort the array in increasing order ; If all elements are equal , then it is not possible ; Else print the sorted array arr [ ] ; Driver Code ; Given array ; Function call
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int compare ( const void * a , const void * b ) { return ( * ( int * ) a - * ( int * ) b ) ; } void printArr ( int arr [ ] , int n ) { qsort ( arr , n , sizeof ( int ) , compare ) ; if ( arr [ 0 ] == arr [ n - 1 ] ) { printf ( " No STRNEWLINE " ) ; } else { printf ( " Yes STRNEWLINE " ) ; for ( int i = 0 ; i < n ; i ++ ) { printf ( " % d ▁ " , arr [ i ] ) ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 1 , 3 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printArr ( arr , N ) ; return 0 ; }
Maximum width of a binary tree | C program to calculate width of binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function protoypes ; Function to get the maximum width of a binary tree ; Get width of each level and compare the width with maximum width so far ; Get width of a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code ; Constructed binary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 ; Function call
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; int getWidth ( struct node * root , int level ) ; int height ( struct node * node ) ; struct node * newNode ( int data ) ; int getMaxWidth ( struct node * root ) { int maxWidth = 0 ; int width ; int h = height ( root ) ; int i ; for ( i = 1 ; i <= h ; i ++ ) { width = getWidth ( root , i ) ; if ( width > maxWidth ) maxWidth = width ; } return maxWidth ; } int getWidth ( struct node * root , int level ) { if ( root == NULL ) return 0 ; if ( level == 1 ) return 1 ; else if ( level > 1 ) return getWidth ( root -> left , level - 1 ) + getWidth ( root -> right , level - 1 ) ; } int height ( struct node * node ) { if ( node == NULL ) return 0 ; else { int lHeight = height ( node -> left ) ; int rHeight = height ( node -> right ) ; return ( lHeight > rHeight ) ? ( lHeight + 1 ) : ( rHeight + 1 ) ; } } 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 ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 6 ) ; root -> right -> right -> right = newNode ( 7 ) ; printf ( " Maximum ▁ width ▁ is ▁ % d ▁ STRNEWLINE " , getMaxWidth ( root ) ) ; getchar ( ) ; return 0 ; }
Maximum width of a binary tree | C program to calculate width of binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function to get height of a binary tree ; Function to get the maximum width of a binary tree ; Create an array that will store count of nodes at each level ; Fill the count array using preorder traversal ; Return the maximum value from count array ; A function that fills count array with count of nodes at every level of given binary tree ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Return the maximum value from count array ; Driver program to test above functions ; Constructed bunary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; int height ( struct node * node ) ; struct node * newNode ( int data ) ; int getMax ( int arr [ ] , int n ) ; void getMaxWidthRecur ( struct node * root , int count [ ] , int level ) ; int getMaxWidth ( struct node * root ) { int width ; int h = height ( root ) ; int * count = ( int * ) calloc ( sizeof ( int ) , h ) ; int level = 0 ; getMaxWidthRecur ( root , count , level ) ; return getMax ( count , h ) ; } void getMaxWidthRecur ( struct node * root , int count [ ] , int level ) { if ( root ) { count [ level ] ++ ; getMaxWidthRecur ( root -> left , count , level + 1 ) ; getMaxWidthRecur ( root -> right , count , level + 1 ) ; } } int height ( struct node * node ) { if ( node == NULL ) return 0 ; else { int lHeight = height ( node -> left ) ; int rHeight = height ( node -> right ) ; return ( lHeight > rHeight ) ? ( lHeight + 1 ) : ( rHeight + 1 ) ; } } 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 ) ; } int getMax ( int arr [ ] , int n ) { int max = arr [ 0 ] ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; } return max ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 6 ) ; root -> right -> right -> right = newNode ( 7 ) ; printf ( " Maximum ▁ width ▁ is ▁ % d ▁ STRNEWLINE " , getMaxWidth ( root ) ) ; getchar ( ) ; return 0 ; }
Program to count leaf nodes in a binary tree | C implementation to find leaf count of a given Binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to get the count of leaf nodes in a binary tree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; create a tree ; get leaf count of the above created tree
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; unsigned int getLeafCount ( struct node * node ) { if ( node == NULL ) return 0 ; if ( node -> left == NULL && node -> right == NULL ) return 1 ; else return getLeafCount ( node -> left ) + getLeafCount ( 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 ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; printf ( " Leaf ▁ count ▁ of ▁ the ▁ tree ▁ is ▁ % d " , getLeafCount ( root ) ) ; getchar ( ) ; return 0 ; }
Greedy Algorithm to find Minimum number of Coins | C program to find minimum number of denominations ; All denominations of Indian Currency ; Initialize result ; Traverse through all denomination ; Find denominations ; Print result ; Driver Code
#include <stdio.h> NEW_LINE #define COINS 9 NEW_LINE #define MAX 20 NEW_LINE int coins [ COINS ] = { 1 , 2 , 5 , 10 , 20 , 50 , 100 , 200 , 2000 } ; void findMin ( int cost ) { int coinList [ MAX ] = { 0 } ; int i , k = 0 ; for ( i = COINS - 1 ; i >= 0 ; i -- ) { while ( cost >= coins [ i ] ) { cost -= coins [ i ] ; coinList [ k ++ ] = coins [ i ] ; } } for ( i = 0 ; i < k ; i ++ ) { printf ( " % d ▁ " , coinList [ i ] ) ; } return ; } int main ( void ) { int n = 93 ; printf ( " Following ▁ is ▁ minimal ▁ number " " of ▁ change ▁ for ▁ % d : ▁ " , n ) ; findMin ( n ) ; return 0 ; }
Connect nodes at same level using constant extra space | Iterative C program to connect nodes at same level using constant extra space ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; This function returns the leftmost child of nodes at the same level as p . This function is used to getNExt right of p 's right child If right child of is NULL then this can also be used for the left child ; Traverse nodes at p ' s ▁ level ▁ and ▁ find ▁ and ▁ return ▁ ▁ the ▁ first ▁ node ' s first child ; If all the nodes at p 's level are leaf nodes then return NULL ; Sets nextRight of all nodes of a tree with root as p ; Set nextRight for root ; set nextRight of all levels one by one ; Connect all childrem nodes of p and children nodes of all other nodes at same level as p ; Set the nextRight pointer for p 's left child ; If q has right child , then right child is nextRight of p and we also need to set nextRight of right child ; Set nextRight for other nodes in pre order fashion ; start from the first node of next level ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / \ 3 90 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; struct node * nextRight ; } ; struct node * newnode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; node -> nextRight = NULL ; return ( node ) ; } struct node * getNextRight ( struct node * p ) { struct node * temp = p -> nextRight ; while ( temp != NULL ) { if ( temp -> left != NULL ) return temp -> left ; if ( temp -> right != NULL ) return temp -> right ; temp = temp -> nextRight ; } return NULL ; } void connect ( struct node * p ) { struct node * temp ; if ( ! p ) return ; p -> nextRight = NULL ; while ( p != NULL ) { struct node * q = p ; while ( q != NULL ) { if ( q -> left ) { if ( q -> right ) q -> left -> nextRight = q -> right ; else q -> left -> nextRight = getNextRight ( q ) ; } if ( q -> right ) q -> right -> nextRight = getNextRight ( q ) ; q = q -> nextRight ; } if ( p -> left ) p = p -> left ; else if ( p -> right ) p = p -> right ; else p = getNextRight ( p ) ; } } int main ( ) { struct node * root = newnode ( 10 ) ; root -> left = newnode ( 8 ) ; root -> right = newnode ( 2 ) ; root -> left -> left = newnode ( 3 ) ; root -> right -> right = newnode ( 90 ) ; connect ( root ) ; printf ( " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ the ▁ tree ▁ " " ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) ▁ STRNEWLINE " ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> data , root -> nextRight ? root -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> left -> data , root -> left -> nextRight ? root -> left -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> right -> data , root -> right -> nextRight ? root -> right -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> left -> left -> data , root -> left -> left -> nextRight ? root -> left -> left -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> right -> right -> data , root -> right -> right -> nextRight ? root -> right -> right -> nextRight -> data : -1 ) ; getchar ( ) ; return 0 ; }
Connect nodes at same level | C program to connect nodes at same level using extended pre - order traversal ; A binary tree node ; Sets the nextRight of root and calls connectRecur ( ) for other nodes ; Set the nextRight for root ; Set the next right for rest of the nodes ( other than root ) ; Set next right of all descendents of p . Assumption : p is a compete binary tree ; Base case ; Set the nextRight pointer for p 's left child ; Set the nextRight pointer for p 's right child p->nextRight will be NULL if p is the right most child at its level ; Set nextRight for other nodes in pre order fashion ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / 3 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void connectRecur ( struct node * p ) ; struct node { int data ; struct node * left ; struct node * right ; struct node * nextRight ; } ; void connect ( struct node * p ) { p -> nextRight = NULL ; connectRecur ( p ) ; } void connectRecur ( struct node * p ) { if ( ! p ) return ; if ( p -> left ) p -> left -> nextRight = p -> right ; if ( p -> right ) p -> right -> nextRight = ( p -> nextRight ) ? p -> nextRight -> left : NULL ; connectRecur ( p -> left ) ; connectRecur ( p -> right ) ; } struct node * newnode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; node -> nextRight = NULL ; return ( node ) ; } int main ( ) { struct node * root = newnode ( 10 ) ; root -> left = newnode ( 8 ) ; root -> right = newnode ( 2 ) ; root -> left -> left = newnode ( 3 ) ; connect ( root ) ; printf ( " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ the ▁ tree ▁ " " ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) ▁ STRNEWLINE " ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> data , root -> nextRight ? root -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> left -> data , root -> left -> nextRight ? root -> left -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> right -> data , root -> right -> nextRight ? root -> right -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> left -> left -> data , root -> left -> left -> nextRight ? root -> left -> left -> nextRight -> data : -1 ) ; return 0 ; }
Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; A utility function to find minimum of two numbers ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which subrpoblem ( s ) to call ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE #include <string.h> NEW_LINE int min ( int a , int b ) { return a < b ? a : b ; } int findMinInsertions ( char str [ ] , int l , int h ) { if ( l > h ) return INT_MAX ; if ( l == h ) return 0 ; if ( l == h - 1 ) return ( str [ l ] == str [ h ] ) ? 0 : 1 ; return ( str [ l ] == str [ h ] ) ? findMinInsertions ( str , l + 1 , h - 1 ) : ( min ( findMinInsertions ( str , l , h - 1 ) , findMinInsertions ( str , l + 1 , h ) ) + 1 ) ; } int main ( ) { char str [ ] = " geeks " ; printf ( " % d " , findMinInsertions ( str , 0 , strlen ( str ) - 1 ) ) ; return 0 ; }
Longest Palindromic Subsequence | DP | C program of above approach ; A utility function to get max of two integers ; Returns the length of the longest palindromic subsequence in seq ; Base Case 1 : If there is only 1 character ; Base Case 2 : If there are only 2 characters and both are same ; If the first and last characters match ; If the first and last characters do not match ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int max ( int x , int y ) { return ( x > y ) ? x : y ; } int lps ( char * seq , int i , int j ) { if ( i == j ) return 1 ; if ( seq [ i ] == seq [ j ] && i + 1 == j ) return 2 ; if ( seq [ i ] == seq [ j ] ) return lps ( seq , i + 1 , j - 1 ) + 2 ; return max ( lps ( seq , i , j - 1 ) , lps ( seq , i + 1 , j ) ) ; } int main ( ) { char seq [ ] = " GEEKSFORGEEKS " ; int n = strlen ( seq ) ; printf ( " The ▁ length ▁ of ▁ the ▁ LPS ▁ is ▁ % d " , lps ( seq , 0 , n - 1 ) ) ; getchar ( ) ; return 0 ; }
Get Level of a node in a Binary Tree | C program to Get Level of a node in a Binary Tree ; A tree node structure ; Helper function for getLevel ( ) . It returns level of the data if data is present in tree , otherwise returns 0. ; Returns level of given data value ; Utility function to create a new Binary Tree node ; Driver code ; Constructing tree given in the above figure
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; int getLevelUtil ( struct node * node , int data , int level ) { if ( node == NULL ) return 0 ; if ( node -> data == data ) return level ; int downlevel = getLevelUtil ( node -> left , data , level + 1 ) ; if ( downlevel != 0 ) return downlevel ; downlevel = getLevelUtil ( node -> right , data , level + 1 ) ; return downlevel ; } int getLevel ( struct node * node , int data ) { return getLevelUtil ( node , data , 1 ) ; } struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int main ( ) { struct node * root ; int x ; root = newNode ( 3 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; for ( x = 1 ; x <= 5 ; x ++ ) { int level = getLevel ( root , x ) ; if ( level ) printf ( " ▁ Level ▁ of ▁ % d ▁ is ▁ % d STRNEWLINE " , x , getLevel ( root , x ) ) ; else printf ( " ▁ % d ▁ is ▁ not ▁ present ▁ in ▁ tree ▁ STRNEWLINE " , x ) ; } getchar ( ) ; return 0 ; }
Finite Automata algorithm for Pattern Searching | C program for Finite Automata Pattern searching Algorithm ; If the character c is same as next character in pattern , then simply increment state ; ns stores the result which is next state ; Start from the largest possible value and stop when you find a prefix which is also suffix ; This function builds the TF table which represents4 Finite Automata for a given pattern ; Prints all occurrences of pat in txt ; Process txt over FA . ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define NO_OF_CHARS 256 NEW_LINE int getNextState ( char * pat , int M , int state , int x ) { if ( state < M && x == pat [ state ] ) return state + 1 ; int ns , i ; for ( ns = state ; ns > 0 ; ns -- ) { if ( pat [ ns - 1 ] == x ) { for ( i = 0 ; i < ns - 1 ; i ++ ) if ( pat [ i ] != pat [ state - ns + 1 + i ] ) break ; if ( i == ns - 1 ) return ns ; } } return 0 ; } void computeTF ( char * pat , int M , int TF [ ] [ NO_OF_CHARS ] ) { int state , x ; for ( state = 0 ; state <= M ; ++ state ) for ( x = 0 ; x < NO_OF_CHARS ; ++ x ) TF [ state ] [ x ] = getNextState ( pat , M , state , x ) ; } void search ( char * pat , char * txt ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int TF [ M + 1 ] [ NO_OF_CHARS ] ; computeTF ( pat , M , TF ) ; int i , state = 0 ; for ( i = 0 ; i < N ; i ++ ) { state = TF [ state ] [ txt [ i ] ] ; if ( state == M ) printf ( " Pattern found at index % d " , i - M + 1 ) ; } } int main ( ) { char * txt = " AABAACAADAABAAABAA " ; char * pat = " AABA " ; search ( pat , txt ) ; return 0 ; }
Find mirror of a given node in Binary tree | C program to find the mirror Node in Binary tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; create new Node and initialize it ; recursive function to find mirror of Node ; if any of the Node is none then Node itself and decendent have no mirror , so return none , no need to further explore ! ; if left Node is target Node , then return right 's key (that is mirror) and vice versa ; first recur external Nodes ; if no mirror found , recur internal Nodes ; interface for mirror search ; Driver ; target Node whose mirror have to be searched
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int key ; struct Node * left , * right ; } ; struct Node * newNode ( int key ) { struct Node * n = ( struct Node * ) malloc ( sizeof ( struct Node * ) ) ; if ( n != NULL ) { n -> key = key ; n -> left = NULL ; n -> right = NULL ; return n ; } else { printf ( " Memory ▁ allocation ▁ failed ! " ) ; exit ( 1 ) ; } } int findMirrorRec ( int target , struct Node * left , struct Node * right ) { if ( left == NULL right == NULL ) return 0 ; if ( left -> key == target ) return right -> key ; if ( right -> key == target ) return left -> key ; int mirror_val = findMirrorRec ( target , left -> left , right -> right ) ; if ( mirror_val ) return mirror_val ; findMirrorRec ( target , left -> right , right -> left ) ; } int findMirror ( struct Node * root , int target ) { if ( root == NULL ) return 0 ; if ( root -> key == target ) return target ; return findMirrorRec ( target , root -> left , root -> right ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> left -> right = newNode ( 7 ) ; root -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> left = newNode ( 8 ) ; root -> right -> left -> right = newNode ( 9 ) ; int target = root -> left -> left -> key ; int mirror = findMirror ( root , target ) ; if ( mirror ) printf ( " Mirror ▁ of ▁ Node ▁ % d ▁ is ▁ Node ▁ % d STRNEWLINE " , target , mirror ) ; else printf ( " Mirror ▁ of ▁ Node ▁ % d ▁ is ▁ NULL ! STRNEWLINE " , target ) ; }
Iterative Search for a key ' x ' in Binary Tree | Iterative level order traversal based method to search in Binary Tree ; 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 search an element x in a given binary tree ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; Queue based level order traversal ; See if current node is same as x ; Remove current node and enqueue its children ; Driver program
#include <iostream> NEW_LINE #include <queue> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * node = new struct node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } bool iterativeSearch ( node * root , int x ) { if ( root == NULL ) return false ; queue < node * > q ; q . push ( root ) ; while ( q . empty ( ) == false ) { node * node = q . front ( ) ; if ( node -> data == x ) return true ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; } return false ; } int main ( void ) { struct node * NewRoot = NULL ; struct node * root = newNode ( 2 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 1 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 4 ) ; iterativeSearch ( root , 6 ) ? cout << " Found STRNEWLINE " : cout << " Not ▁ Found STRNEWLINE " ; iterativeSearch ( root , 12 ) ? cout << " Found STRNEWLINE " : cout << " Not ▁ Found STRNEWLINE " ; return 0 ; }
Populate Inorder Successor for all nodes | C # program to populate inorder traversal of all nodes ; An implementation that doesn 't use static variable A wrapper over populateNextRecur ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; Set next of all descendants of p by traversing them in reverse Inorder ; First set the next pointer in right subtree ; Set the next as previously visited node in reverse Inorder ; Change the prev for subsequent node ; Finally , set the next pointer in right subtree
struct node { int data ; struct node * left ; struct node * right ; struct node * next ; } void populateNext ( struct node * root ) { struct node * next = NULL ; populateNextRecur ( root , & next ) ; } void populateNextRecur ( struct node * p , struct node * * next_ref ) { if ( p ) { populateNextRecur ( p -> right , next_ref ) ; p -> next = * next_ref ; * next_ref = p ; populateNextRecur ( p -> left , next_ref ) ; } }
Given a binary tree , how do you remove all the half nodes ? | C program to remove all half nodes ; Binary tree node ; ; For inorder traversal ; Removes all nodes with only one child and returns new root ( note that root may change ) ; if current nodes is a half node with left child NULL left , then it 's right child is returned and replaces it in the given tree ; if current nodes is a half node with right child NULL right , then it 's right child is returned and replaces it in the given tree ; Driver program
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void printInoder ( struct node * root ) { if ( root != NULL ) { printInoder ( root -> left ) ; printf ( " % d ▁ " , root -> data ) ; printInoder ( root -> right ) ; } } struct node * RemoveHalfNodes ( struct node * root ) { if ( root == NULL ) return NULL ; root -> left = RemoveHalfNodes ( root -> left ) ; root -> right = RemoveHalfNodes ( root -> right ) ; if ( root -> left == NULL && root -> right == NULL ) return root ; if ( root -> left == NULL ) { struct node * new_root = root -> right ; free ( root ) ; return new_root ; } if ( root -> right == NULL ) { struct node * new_root = root -> left ; free ( root ) ; return new_root ; } return root ; } int main ( void ) { struct node * NewRoot = NULL ; struct node * root = newNode ( 2 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 1 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 4 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ given ▁ tree ▁ STRNEWLINE " ) ; printInoder ( root ) ; NewRoot = RemoveHalfNodes ( root ) ; printf ( " Inorder traversal of the modified tree " printInoder ( NewRoot ) ; return 0 ; }
Program to print all substrings of a given string | C program for the above approach ; outermost for loop this is for the selection of starting point ; 2 nd for loop is for selection of ending point ; 3 rd loop is for printing from starting point to ending point ; changing the line after printing from starting point to ending point ; Driver Code ; calling the method to print the substring
#include <stdio.h> NEW_LINE void printSubstrings ( char str [ ] ) { for ( int start = 0 ; str [ start ] != ' \0' ; start ++ ) { for ( int end = start ; str [ end ] != ' \0' ; end ++ ) { for ( int i = start ; i <= end ; i ++ ) { printf ( " % c " , str [ i ] ) ; } printf ( " STRNEWLINE " ) ; } } } int main ( ) { char str [ ] = { ' a ' , ' b ' , ' c ' , ' d ' , ' \0' } ; printSubstrings ( str ) ; return 0 ; }
Sudoku | Backtracking | ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Checks whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return 0 ; Check if we find the same num in the similar column , we return 0 ; Check if we find the same num in the particular 3 * 3 matrix , we return 0 ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; Check if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; assigning the num in the current ( row , col ) position of the grid and assuming our assigned num in the position is correct ; Checking for next possibility with next column ; Removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; 0 means unassigned cells
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define N 9 NEW_LINE void print ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) printf ( " % d ▁ " , arr [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } int isSafe ( int grid [ N ] [ N ] , int row , int col , int num ) { for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ row ] [ x ] == num ) return 0 ; for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ x ] [ col ] == num ) return 0 ; int startRow = row - row % 3 , startCol = col - col % 3 ; for ( int i = 0 ; i < 3 ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) if ( grid [ i + startRow ] [ j + startCol ] == num ) return 0 ; return 1 ; } int solveSuduko ( int grid [ N ] [ N ] , int row , int col ) { if ( row == N - 1 && col == N ) return 1 ; if ( col == N ) { row ++ ; col = 0 ; } if ( grid [ row ] [ col ] > 0 ) return solveSuduko ( grid , row , col + 1 ) ; for ( int num = 1 ; num <= N ; num ++ ) { if ( isSafe ( grid , row , col , num ) == 1 ) { grid [ row ] [ col ] = num ; if ( solveSuduko ( grid , row , col + 1 ) == 1 ) return 1 ; } grid [ row ] [ col ] = 0 ; } return 0 ; } int main ( ) { int grid [ N ] [ N ] = { { 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 } , { 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 } , { 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 } , { 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 } , { 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 } , { 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 } , { 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 } } ; if ( solveSuduko ( grid , 0 , 0 ) == 1 ) print ( grid ) ; else printf ( " No ▁ solution ▁ exists " ) ; return 0 ; }
Subset Sum | Backtracking | ; prints subset found ; qsort compare function ; inputs s - set vector t - tuplet vector s_size - set size t_size - tuplet size so far sum - sum so far ite - nodes count target_sum - sum to be found ; We found sum ; constraint check ; Exclude previous added item and consider next candidate ; constraint check ; generate nodes along the breadth ; consider next level node ( along depth ) ; Wrapper that prints subsets that sum to target_sum ; sort the set ; Driver Code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define ARRAYSIZE ( a ) (sizeof(a))/(sizeof(a[0])) NEW_LINE static int total_nodes ; void printSubset ( int A [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { printf ( " % * d " , 5 , A [ i ] ) ; } printf ( " STRNEWLINE " ) ; } int comparator ( const void * pLhs , const void * pRhs ) { int * lhs = ( int * ) pLhs ; int * rhs = ( int * ) pRhs ; return * lhs > * rhs ; } void subset_sum ( int s [ ] , int t [ ] , int s_size , int t_size , int sum , int ite , int const target_sum ) { total_nodes ++ ; if ( target_sum == sum ) { printSubset ( t , t_size ) ; if ( ite + 1 < s_size && sum - s [ ite ] + s [ ite + 1 ] <= target_sum ) { subset_sum ( s , t , s_size , t_size - 1 , sum - s [ ite ] , ite + 1 , target_sum ) ; } return ; } else { if ( ite < s_size && sum + s [ ite ] <= target_sum ) { for ( int i = ite ; i < s_size ; i ++ ) { t [ t_size ] = s [ i ] ; if ( sum + s [ i ] <= target_sum ) { subset_sum ( s , t , s_size , t_size + 1 , sum + s [ i ] , i + 1 , target_sum ) ; } } } } } void generateSubsets ( int s [ ] , int size , int target_sum ) { int * tuplet_vector = ( int * ) malloc ( size * sizeof ( int ) ) ; int total = 0 ; qsort ( s , size , sizeof ( int ) , & comparator ) ; for ( int i = 0 ; i < size ; i ++ ) { total += s [ i ] ; } if ( s [ 0 ] <= target_sum && total >= target_sum ) { subset_sum ( s , tuplet_vector , size , 0 , 0 , 0 , target_sum ) ; } free ( tuplet_vector ) ; } int main ( ) { int weights [ ] = { 15 , 22 , 14 , 26 , 32 , 9 , 16 , 8 } ; int target = 53 ; int size = ARRAYSIZE ( weights ) ; generateSubsets ( weights , size , target ) ; printf ( " Nodes ▁ generated ▁ % d STRNEWLINE " , total_nodes ) ; return 0 ; }
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | C program to check if given array has 2 elements whose sum is equal to the given value ; function to check for the given sum in the array ; checking for condition ; Driver Code
#include <stdio.h> NEW_LINE #define MAX 100000 NEW_LINE void printPairs ( int arr [ ] , int arr_size , int sum ) { int i , temp ; bool s [ MAX ] = { 0 } ; for ( i = 0 ; i < arr_size ; i ++ ) { temp = sum - arr [ i ] ; if ( s [ temp ] == 1 ) printf ( " Pair ▁ with ▁ given ▁ sum ▁ % d ▁ is ▁ ( % d , ▁ % d ) ▁ n " , sum , arr [ i ] , temp ) ; s [ arr [ i ] ] = 1 ; } } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int n = 16 ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; printPairs ( A , arr_size , n ) ; getchar ( ) ; return 0 ; }
Modular exponentiation ( Recursive ) | Recursive C program to compute modular power ; Base cases ; If B is even ; If B is odd ; Driver program to test above functions
#include <stdio.h> NEW_LINE int exponentMod ( int A , int B , int C ) { if ( A == 0 ) return 0 ; if ( B == 0 ) return 1 ; long y ; if ( B % 2 == 0 ) { y = exponentMod ( A , B / 2 , C ) ; y = ( y * y ) % C ; } else { y = A % C ; y = ( y * exponentMod ( A , B - 1 , C ) % C ) % C ; } return ( int ) ( ( y + C ) % C ) ; } int main ( ) { int A = 2 , B = 5 , C = 13 ; printf ( " Power ▁ is ▁ % d " , exponentMod ( A , B , C ) ) ; return 0 ; }
Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Change x to x ^ 2
int power ( int x , unsigned int y ) { int res = 1 ; while ( y > 0 ) { if ( y & 1 ) res = res * x ; y = y >> 1 ; x = x * x ; } return res ; }
Egg Dropping Puzzle | DP | ; A utility function to get maximum of two integers ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; If there are no floors , then no trials needed . OR if there is one floor , one trial needed . ; We need k trials for one egg and k floors ; Consider all droppings from 1 st floor to kth floor and return the minimum of these values plus 1. ; Driver code
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } int eggDrop ( int n , int k ) { if ( k == 1 k == 0 ) return k ; if ( n == 1 ) return k ; int min = INT_MAX , x , res ; for ( x = 1 ; x <= k ; x ++ ) { res = max ( eggDrop ( n - 1 , x - 1 ) , eggDrop ( n , k - x ) ) ; if ( res < min ) min = res ; } return min + 1 ; } int main ( ) { int n = 2 , k = 10 ; printf ( " nMinimum ▁ number ▁ of ▁ trials ▁ in ▁ " " worst ▁ case ▁ with ▁ % d ▁ eggs ▁ and ▁ " " % d ▁ floors ▁ is ▁ % d ▁ STRNEWLINE " , n , k , eggDrop ( n , k ) ) ; return 0 ; }
Binary Tree | Set 1 ( Introduction ) | ; struct containing left and right child of current node and key value ; newNode ( ) allocates a new node with the given data and NULL left and right pointers . ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; getchar ( ) ; return 0 ; }
Find maximum ( or minimum ) in Binary Tree | C program to find maximum and minimum in a Binary Tree ; A tree node ; A utility function to create a new node ; Returns maximum value in a given Binary Tree ; Base case ; Return maximum of 3 values : 1 ) Root 's data 2) Max in Left Subtree 3) Max in right subtree ; Driver code ; Function call
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int findMax ( struct Node * root ) { if ( root == NULL ) return INT_MIN ; int res = root -> data ; int lres = findMax ( root -> left ) ; int rres = findMax ( root -> right ) ; if ( lres > res ) res = lres ; if ( rres > res ) res = rres ; return res ; } int main ( void ) { struct Node * NewRoot = NULL ; struct Node * root = newNode ( 2 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 1 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 4 ) ; printf ( " Maximum ▁ element ▁ is ▁ % d ▁ STRNEWLINE " , findMax ( root ) ) ; return 0 ; }
Find maximum ( or minimum ) in Binary Tree | Returns minimum value in a given Binary Tree
int findMin ( struct Node * root ) { if ( root == NULL ) return INT_MAX ; int res = root -> data ; int lres = findMin ( root -> left ) ; int rres = findMin ( root -> right ) ; if ( lres < res ) res = lres ; if ( rres < res ) res = rres ; return res ; }
Extract Leaves of a Binary Tree in a Doubly Linked List | C program to extract leaves of a Binary Tree in a Doubly Linked List ; Structure for tree and linked list ; Main function which extracts all leaves from given Binary Tree . The function returns new root of Binary Tree ( Note that root may changeif Binary Tree has only one node ) . The function also sets * head_ref as head of doubly linked list . left pointer of tree is used as prev in DLL and right pointer is used as next ; Utility function for allocating node for Binary Tree . ; Utility function for printing tree in In - Order . ; Utility function for printing double linked list . ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * left , * right ; } ; struct Node * extractLeafList ( struct Node * root , struct Node * * head_ref ) { if ( root == NULL ) return NULL ; if ( root -> left == NULL && root -> right == NULL ) { root -> right = * head_ref ; if ( * head_ref != NULL ) ( * head_ref ) -> left = root ; return NULL ; } root -> right = extractLeafList ( root -> right , head_ref ) ; root -> left = extractLeafList ( root -> left , head_ref ) ; return root ; } struct Node * newNode ( int data ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } void print ( struct Node * root ) { if ( root != NULL ) { print ( root -> left ) ; printf ( " % d ▁ " , root -> data ) ; print ( root -> right ) ; } } void printList ( struct Node * head ) { while ( head ) { printf ( " % d ▁ " , head -> data ) ; head = head -> right ; } } int main ( ) { struct Node * head = NULL ; struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> left -> left -> left = newNode ( 7 ) ; root -> left -> left -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 9 ) ; root -> right -> right -> right = newNode ( 10 ) ; printf ( " Inorder ▁ Trvaersal ▁ of ▁ given ▁ Tree ▁ is : STRNEWLINE " ) ; print ( root ) ; root = extractLeafList ( root , & head ) ; printf ( " Extracted Double Linked list is : " printList ( head ) ; printf ( " Inorder traversal of modified tree is : " print ( root ) ; return 0 ; }
Find n | C program for nth nodes of inorder traversals ; 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 . ; Given a binary tree , print its nth nodes of inorder ; first recur on left child ; when count = n then print element ; now recur on right child ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ) ; } void NthInorder ( struct Node * node , int n ) { static int count = 0 ; if ( node == NULL ) return ; if ( count <= n ) { NthInorder ( node -> left , n ) ; count ++ ; if ( count == n ) printf ( " % d ▁ " , node -> data ) ; NthInorder ( node -> right , n ) ; } } int main ( ) { struct Node * root = newNode ( 10 ) ; root -> left = newNode ( 20 ) ; root -> right = newNode ( 30 ) ; root -> left -> left = newNode ( 40 ) ; root -> left -> right = newNode ( 50 ) ; int n = 4 ; NthInorder ( root , n ) ; return 0 ; }
QuickSort Tail Call Optimization ( Reducing worst case space to Log n ) | A Simple implementation of QuickSort that makes two two recursive calls . ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition
void quickSort ( int arr [ ] , int low , int high ) { if ( low < high ) { int pi = partition ( arr , low , high ) ; quickSort ( arr , low , pi - 1 ) ; quickSort ( arr , pi + 1 , high ) ; } }
Count all possible strings that can be generated by placing spaces | C program to implement the above approach ; Function to count the number of strings that can be generated by placing spaces between pair of adjacent characters ; Length of the string ; Count of positions for spaces ; Count of possible strings ; Driver Code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE long long int countNumberOfStrings ( char * s ) { int length = strlen ( s ) ; int n = length - 1 ; long long int count = pow ( 2 , n ) ; return count ; } int main ( ) { char S [ ] = " ABCD " ; printf ( " % lld " , countNumberOfStrings ( S ) ) ; return 0 ; }
Modify given array to make sum of odd and even indexed elements same | C ++ program for the above approach ; Function to modify array to make sum of odd and even indexed elements equal ; Stores the count of 0 s , 1 s ; Stores sum of odd and even indexed elements respectively ; Count 0 s ; Count 1 s ; Calculate odd_sum and even_sum ; If both are equal ; Print the original array ; Otherwise ; Print all the 0 s ; For checking even or odd ; Update total count of 1 s ; Print all 1 s ; Driver Code ; Given array arr [ ] ; Function Call
#include <stdio.h> NEW_LINE void makeArraySumEqual ( int a [ ] , int N ) { int count_0 = 0 , count_1 = 0 ; int odd_sum = 0 , even_sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( a [ i ] == 0 ) count_0 ++ ; else count_1 ++ ; if ( ( i + 1 ) % 2 == 0 ) even_sum += a [ i ] ; else if ( ( i + 1 ) % 2 > 0 ) odd_sum += a [ i ] ; } if ( odd_sum == even_sum ) { for ( int i = 0 ; i < N ; i ++ ) printf ( " % d ▁ " , a [ i ] ) ; } else { if ( count_0 >= N / 2 ) { for ( int i = 0 ; i < count_0 ; i ++ ) printf ( "0 ▁ " ) ; } else { int is_Odd = count_1 % 2 ; count_1 -= is_Odd ; for ( int i = 0 ; i < count_1 ; i ++ ) printf ( "1 ▁ " ) ; } } } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; makeArraySumEqual ( arr , N ) ; return 0 ; }
Count of N digit Numbers whose sum of every K consecutive digits is equal | C program for the above approach ; Function to count the number of N - digit numbers such that sum of every k consecutive digits are equal ; Range of numbers ; Extract digits of the number ; Store the sum of first K digits ; Check for every k - consecutive digits using sliding window ; Driver Code ; Given integer N and K
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE int countDigitSum ( int N , int K ) { int l = ( int ) pow ( 10 , N - 1 ) , r = ( int ) pow ( 10 , N ) - 1 ; int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { int num = i ; int digits [ N ] ; for ( int j = N - 1 ; j >= 0 ; j -- ) { digits [ j ] = num % 10 ; num /= 10 ; } int sum = 0 , flag = 0 ; for ( int j = 0 ; j < K ; j ++ ) sum += digits [ j ] ; for ( int j = K ; j < N ; j ++ ) { if ( sum - digits [ j - K ] + digits [ j ] != sum ) { flag = 1 ; break ; } } if ( flag == 0 ) count ++ ; } return count ; } int main ( ) { int N = 2 , K = 1 ; printf ( " % d " , countDigitSum ( N , K ) ) ; return 0 ; }
Find if possible to visit every nodes in given Graph exactly once based on given conditions | C ++ program for above approach . ; Function to find print path ; If a [ 0 ] is 1 ; Printing path ; Seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; Printing path ; If a [ N - 1 ] = 0 ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findpath ( int N , int a [ ] ) { if ( a [ 0 ] ) { printf ( " % d ▁ " , N + 1 ) ; for ( int i = 1 ; i <= N ; i ++ ) printf ( " % d ▁ " , i ) ; return ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( ! a [ i ] && a [ i + 1 ] ) { for ( int j = 1 ; j <= i ; j ++ ) printf ( " % d ▁ " , j ) ; printf ( " % d ▁ " , N + 1 ) ; for ( int j = i + 1 ; j <= N ; j ++ ) printf ( " % d ▁ " , j ) ; return ; } } for ( int i = 1 ; i <= N ; i ++ ) printf ( " % d ▁ " , i ) ; printf ( " % d ▁ " , N + 1 ) ; } int main ( ) { int N = 3 , arr [ ] = { 0 , 1 , 0 } ; findpath ( N , arr ) ; }
Printing Items in 0 / 1 Knapsack | CPP code for Dynamic Programming based solution for 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Prints the items which are put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; stores the result of Knapsack ; either the result comes from the top ( K [ i - 1 ] [ w ] ) or from ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] ) as in Knapsack table . If it comes from the latter one / it means the item is included . ; This item is included . ; Since this weight is included its value is deducted ; Driver code
#include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } void printknapSack ( int W , int wt [ ] , int val [ ] , int n ) { int i , w ; int K [ n + 1 ] [ W + 1 ] ; for ( i = 0 ; i <= n ; i ++ ) { for ( w = 0 ; w <= W ; w ++ ) { if ( i == 0 w == 0 ) K [ i ] [ w ] = 0 ; else if ( wt [ i - 1 ] <= w ) K [ i ] [ w ] = max ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] , K [ i - 1 ] [ w ] ) ; else K [ i ] [ w ] = K [ i - 1 ] [ w ] ; } } int res = K [ n ] [ W ] ; printf ( " % d STRNEWLINE " , res ) ; w = W ; for ( i = n ; i > 0 && res > 0 ; i -- ) { if ( res == K [ i - 1 ] [ w ] ) continue ; else { printf ( " % d ▁ " , wt [ i - 1 ] ) ; res = res - val [ i - 1 ] ; w = w - wt [ i - 1 ] ; } } } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; printknapSack ( W , wt , val , n ) ; return 0 ; }
Optimal Binary Search Tree | DP | A naive recursive implementation of optimal binary search tree problem ; A recursive function to calculate cost of optimal binary search tree ; Base cases if ( j < i ) no elements in this subarray ; one element in this subarray ; Get sum of freq [ i ] , freq [ i + 1 ] , ... freq [ j ] ; Initialize minimum value ; One by one consider all elements as root and recursively find cost of the BST , compare the cost with min and update min if needed ; Return minimum value ; The main function that calculates minimum cost of a Binary Search Tree . It mainly uses optCost ( ) to find the optimal cost . ; Here array keys [ ] is assumed to be sorted in increasing order . If keys [ ] is not sorted , then add code to sort keys , and rearrange freq [ ] accordingly . ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE int optCost ( int freq [ ] , int i , int j ) { return 0 ; if ( j == i ) return freq [ i ] ; int fsum = sum ( freq , i , j ) ; int min = INT_MAX ; for ( int r = i ; r <= j ; ++ r ) { int cost = optCost ( freq , i , r - 1 ) + optCost ( freq , r + 1 , j ) ; if ( cost < min ) min = cost ; } return min + fsum ; } int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { return optCost ( freq , 0 , n - 1 ) ; } int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } int main ( ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = sizeof ( keys ) / sizeof ( keys [ 0 ] ) ; printf ( " Cost ▁ of ▁ Optimal ▁ BST ▁ is ▁ % d ▁ " , optimalSearchTree ( keys , freq , n ) ) ; return 0 ; }
Word Wrap Problem | DP | A Dynamic programming solution for Word Wrap Problem ; A utility function to print the solution ; l [ ] represents lengths of different words in input sequence . For example , l [ ] = { 3 , 2 , 2 , 5 } is for a sentence like " aaa ▁ bb ▁ cc ▁ ddddd " . n is size of l [ ] and M is line width ( maximum no . of characters that can fit in a line ) ; extras [ i ] [ j ] will have number of extra spaces if words from i to j are put in a single line ; lc [ i ] [ j ] will have cost of a line which has words from i to j ; c [ i ] will have total cost of optimal arrangement of words from 1 to i ; p [ ] is used to print the solution . ; calculate extra spaces in a single line . The value extra [ i ] [ j ] indicates extra spaces if words from word number i to j are placed in a single line ; Calculate line cost corresponding to the above calculated extra spaces . The value lc [ i ] [ j ] indicates cost of putting words from word number i to j in a single line ; Calculate minimum cost and find minimum cost arrangement . The value c [ j ] indicates optimized cost to arrange words from word number 1 to j . ; Driver program to test above functions
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE #define INF INT_MAX NEW_LINE int printSolution ( int p [ ] , int n ) ; void solveWordWrap ( int l [ ] , int n , int M ) { int extras [ n + 1 ] [ n + 1 ] ; int lc [ n + 1 ] [ n + 1 ] ; int c [ n + 1 ] ; int p [ n + 1 ] ; int i , j ; for ( i = 1 ; i <= n ; i ++ ) { extras [ i ] [ i ] = M - l [ i - 1 ] ; for ( j = i + 1 ; j <= n ; j ++ ) extras [ i ] [ j ] = extras [ i ] [ j - 1 ] - l [ j - 1 ] - 1 ; } for ( i = 1 ; i <= n ; i ++ ) { for ( j = i ; j <= n ; j ++ ) { if ( extras [ i ] [ j ] < 0 ) lc [ i ] [ j ] = INF ; else if ( j == n && extras [ i ] [ j ] >= 0 ) lc [ i ] [ j ] = 0 ; else lc [ i ] [ j ] = extras [ i ] [ j ] * extras [ i ] [ j ] ; } } c [ 0 ] = 0 ; for ( j = 1 ; j <= n ; j ++ ) { c [ j ] = INF ; for ( i = 1 ; i <= j ; i ++ ) { if ( c [ i - 1 ] != INF && lc [ i ] [ j ] != INF && ( c [ i - 1 ] + lc [ i ] [ j ] < c [ j ] ) ) { c [ j ] = c [ i - 1 ] + lc [ i ] [ j ] ; p [ j ] = i ; } } } printSolution ( p , n ) ; } int printSolution ( int p [ ] , int n ) { int k ; if ( p [ n ] == 1 ) k = 1 ; else k = printSolution ( p , p [ n ] - 1 ) + 1 ; printf ( " Line ▁ number ▁ % d : ▁ From ▁ word ▁ no . ▁ % d ▁ to ▁ % d ▁ STRNEWLINE " , k , p [ n ] , n ) ; return k ; } int main ( ) { int l [ ] = { 3 , 2 , 2 , 5 } ; int n = sizeof ( l ) / sizeof ( l [ 0 ] ) ; int M = 6 ; solveWordWrap ( l , n , M ) ; return 0 ; }
Egg Dropping Puzzle | DP | A Dynamic Programming based for the Egg Dropping Puzzle ; A utility function to get maximum of two integers ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; A 2D table where entry eggFloor [ i ] [ j ] will represent minimum number of trials needed for i eggs and j floors . ; We need one trial for one floor and 0 trials for 0 floors ; We always need j trials for one egg and j floors . ; Fill rest of the entries in table using optimal substructure property ; eggFloor [ n ] [ k ] holds the result ; Driver program to test to pront printDups
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } int eggDrop ( int n , int k ) { int eggFloor [ n + 1 ] [ k + 1 ] ; int res ; int i , j , x ; for ( i = 1 ; i <= n ; i ++ ) { eggFloor [ i ] [ 1 ] = 1 ; eggFloor [ i ] [ 0 ] = 0 ; } for ( j = 1 ; j <= k ; j ++ ) eggFloor [ 1 ] [ j ] = j ; for ( i = 2 ; i <= n ; i ++ ) { for ( j = 2 ; j <= k ; j ++ ) { eggFloor [ i ] [ j ] = INT_MAX ; for ( x = 1 ; x <= j ; x ++ ) { res = 1 + max ( eggFloor [ i - 1 ] [ x - 1 ] , eggFloor [ i ] [ j - x ] ) ; if ( res < eggFloor [ i ] [ j ] ) eggFloor [ i ] [ j ] = res ; } } } return eggFloor [ n ] [ k ] ; } int main ( ) { int n = 2 , k = 36 ; printf ( " Minimum number of trials " STRNEWLINE TABSYMBOL TABSYMBOL " in worst case with % d eggs and " STRNEWLINE TABSYMBOL TABSYMBOL " % d floors is % d " , n , k , eggDrop ( n , k ) ) ; return 0 ; }
0 | A Naive recursive implementation of 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Returns the maximum value that can be put in a knapsack of capacity W ; Base Case ; If weight of the nth item is more than Knapsack capacity W , then this item cannot be included in the optimal solution ; Return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; Driver program to test above function
#include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } int knapSack ( int W , int wt [ ] , int val [ ] , int n ) { if ( n == 0 W == 0 ) return 0 ; if ( wt [ n - 1 ] > W ) return knapSack ( W , wt , val , n - 1 ) ; else return max ( val [ n - 1 ] + knapSack ( W - wt [ n - 1 ] , wt , val , n - 1 ) , knapSack ( W , wt , val , n - 1 ) ) ; } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; printf ( " % d " , knapSack ( W , wt , val , n ) ) ; return 0 ; }
Longest Increasing Subsequence | DP | A Naive C recursive implementation of LIS problem ; stores the LIS ; To make use of recursive calls , thisfunction must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base case ; ' max _ ending _ here ' is length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] ... arr [ n - 2 ] . If arr [ i - 1 ] is smaller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare max_ending_here with the overall max . And update the overall max if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; The max variable holds the result ; The function _lis ( ) stores its result in max ; returns max ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE let max_ref ; int _lis ( int arr [ ] , int n , int * max_ref ) { if ( n == 1 ) return 1 ; int res , max_ending_here = 1 ; for ( int i = 1 ; i < n ; i ++ ) { res = _lis ( arr , i , max_ref ) ; if ( arr [ i - 1 ] < arr [ n - 1 ] && res + 1 > max_ending_here ) max_ending_here = res + 1 ; } if ( * max_ref < max_ending_here ) * max_ref = max_ending_here ; return max_ending_here ; } int lis ( int arr [ ] , int n ) { int max = 1 ; _lis ( arr , n , & max ) ; return max ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length ▁ of ▁ lis ▁ is ▁ % d " , lis ( arr , n ) ) ; return 0 ; }
Rabin | Following program is a C implementation of Rabin Karp Algorithm given in the CLRS book ; d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; int p = 0 ; hash value for pattern int t = 0 ; hash value for txt ; The value of h would be " pow ( d , ▁ M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern . If the hash values match then only check for characters on by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative value of t , converting it to positive ; Driver Code ; A prime number ; function call
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define d 256 NEW_LINE void search ( char pat [ ] , char txt [ ] , int q ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int i , j ; int h = 1 ; for ( i = 0 ; i < M - 1 ; i ++ ) h = ( h * d ) % q ; for ( i = 0 ; i < M ; i ++ ) { p = ( d * p + pat [ i ] ) % q ; t = ( d * t + txt [ i ] ) % q ; } for ( i = 0 ; i <= N - M ; i ++ ) { if ( p == t ) { for ( j = 0 ; j < M ; j ++ ) { if ( txt [ i + j ] != pat [ j ] ) break ; } if ( j == M ) printf ( " Pattern ▁ found ▁ at ▁ index ▁ % d ▁ STRNEWLINE " , i ) ; } if ( i < N - M ) { t = ( d * ( t - txt [ i ] * h ) + txt [ i + M ] ) % q ; if ( t < 0 ) t = ( t + q ) ; } } } int main ( ) { char txt [ ] = " GEEKS ▁ FOR ▁ GEEKS " ; char pat [ ] = " GEEK " ; int q = 101 ; search ( pat , txt , q ) ; return 0 ; }
The Knight 's tour problem | Backtracking | C program for Knight Tour problem ; A utility function to check if i , j are valid indexes for N * N chessboard ; A utility function to print solution matrix sol [ N ] [ N ] ; This function solves the Knight Tour problem using Backtracking . This function mainly uses solveKTUtil ( ) to solve the problem . It returns false if no complete tour is possible , otherwise return true and prints the tour . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; Initialization of solution matrix ; xMove [ ] and yMove [ ] define next move of Knight . xMove [ ] is for next value of x coordinate yMove [ ] is for next value of y coordinate ; Since the Knight is initially at the first block ; Start from 0 , 0 and explore all tours using solveKTUtil ( ) ; A recursive utility function to solve Knight Tour problem ; Try all next moves from the current coordinate x , y ; backtracking ; Driver Code ; Function Call
#include <stdio.h> NEW_LINE #define N 8 NEW_LINE int solveKTUtil ( int x , int y , int movei , int sol [ N ] [ N ] , int xMove [ ] , int yMove [ ] ) ; int isSafe ( int x , int y , int sol [ N ] [ N ] ) { return ( x >= 0 && x < N && y >= 0 && y < N && sol [ x ] [ y ] == -1 ) ; } void printSolution ( int sol [ N ] [ N ] ) { for ( int x = 0 ; x < N ; x ++ ) { for ( int y = 0 ; y < N ; y ++ ) printf ( " ▁ % 2d ▁ " , sol [ x ] [ y ] ) ; printf ( " STRNEWLINE " ) ; } } int solveKT ( ) { int sol [ N ] [ N ] ; for ( int x = 0 ; x < N ; x ++ ) for ( int y = 0 ; y < N ; y ++ ) sol [ x ] [ y ] = -1 ; int xMove [ 8 ] = { 2 , 1 , -1 , -2 , -2 , -1 , 1 , 2 } ; int yMove [ 8 ] = { 1 , 2 , 2 , 1 , -1 , -2 , -2 , -1 } ; sol [ 0 ] [ 0 ] = 0 ; if ( solveKTUtil ( 0 , 0 , 1 , sol , xMove , yMove ) == 0 ) { printf ( " Solution ▁ does ▁ not ▁ exist " ) ; return 0 ; } else printSolution ( sol ) ; return 1 ; } int solveKTUtil ( int x , int y , int movei , int sol [ N ] [ N ] , int xMove [ N ] , int yMove [ N ] ) { int k , next_x , next_y ; if ( movei == N * N ) return 1 ; for ( k = 0 ; k < 8 ; k ++ ) { next_x = x + xMove [ k ] ; next_y = y + yMove [ k ] ; if ( isSafe ( next_x , next_y , sol ) ) { sol [ next_x ] [ next_y ] = movei ; if ( solveKTUtil ( next_x , next_y , movei + 1 , sol , xMove , yMove ) == 1 ) return 1 ; else sol [ next_x ] [ next_y ] = -1 ; } } return 0 ; } int main ( ) { solveKT ( ) ; return 0 ; }
m Coloring Problem | Backtracking | ; Number of vertices in the graph ; A utility function to print solution ; check if the colored graph is safe or not ; check for every edge ; This function solves the m Coloring problem using recursion . It returns false if the m colours cannot be assigned , otherwise , return true and prints assignments of colours to all vertices . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; if current index reached end ; if coloring is safe ; Print the solution ; Assign each color from 1 to m ; Recur of the rest vertices ; Driver program to test above function ; Create following graph and test whether it is 3 colorable ( 3 ) -- - ( 2 ) | / | | / | | / | ( 0 ) -- - ( 1 ) ; Number of colors ; Initialize all color values as 0. This initialization is needed correct functioning of isSafe ( )
#include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE #define V 4 NEW_LINE void printSolution ( int color [ ] ) ; void printSolution ( int color [ ] ) { printf ( " Solution ▁ Exists : " " ▁ Following ▁ are ▁ the ▁ assigned ▁ colors ▁ STRNEWLINE " ) ; for ( int i = 0 ; i < V ; i ++ ) printf ( " ▁ % d ▁ " , color [ i ] ) ; printf ( " STRNEWLINE " ) ; } bool isSafe ( bool graph [ V ] [ V ] , int color [ ] ) { for ( int i = 0 ; i < V ; i ++ ) for ( int j = i + 1 ; j < V ; j ++ ) if ( graph [ i ] [ j ] && color [ j ] == color [ i ] ) return false ; return true ; } bool graphColoring ( bool graph [ V ] [ V ] , int m , int i , int color [ V ] ) { if ( i == V ) { if ( isSafe ( graph , color ) ) { printSolution ( color ) ; return true ; } return false ; } for ( int j = 1 ; j <= m ; j ++ ) { color [ i ] = j ; if ( graphColoring ( graph , m , i + 1 , color ) ) return true ; color [ i ] = 0 ; } return false ; } int main ( ) { bool graph [ V ] [ V ] = { { 0 , 1 , 1 , 1 } , { 1 , 0 , 1 , 0 } , { 1 , 1 , 0 , 1 } , { 1 , 0 , 1 , 0 } , } ; int m = 3 ; int color [ V ] ; for ( int i = 0 ; i < V ; i ++ ) color [ i ] = 0 ; if ( ! graphColoring ( graph , m , 0 , color ) ) printf ( " Solution ▁ does ▁ not ▁ exist " ) ; return 0 ; }
Logarithm tricks for Competitive Programming | C implementation to find the previous and next power of K ; Function to return the highest power of k less than or equal to n ; Function to return the smallest power of k greater than or equal to n ; Driver Code
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE int prevPowerofK ( int n , int k ) { int p = ( int ) ( log ( n ) / log ( k ) ) ; return ( int ) pow ( k , p ) ; } int nextPowerOfK ( int n , int k ) { return prevPowerofK ( n , k ) * k ; } int main ( ) { int N = 7 ; int K = 2 ; printf ( " % d ▁ " , prevPowerofK ( N , K ) ) ; printf ( " % d STRNEWLINE " , nextPowerOfK ( N , K ) ) ; return 0 ; }
Program to find HCF ( Highest Common Factor ) of 2 Numbers | C program to find GCD of two numbers ; Recursive function to return gcd of a and b ; Driver program to test above function
#include <stdio.h> NEW_LINE int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int main ( ) { int a = 98 , b = 56 ; printf ( " GCD ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ " , a , b , gcd ( a , b ) ) ; return 0 ; }
Check whether a number is semiprime or not | C Program to check whether number is semiprime or not ; Utility function to check whether number is semiprime or not ; If number is greater than 1 , add it to the count variable as it indicates the number remain is prime number ; Return '1' if count is equal to '2' else return '0' ; Function to print ' True ' or ' False ' according to condition of semiprime ; Driver code
#include <stdio.h> NEW_LINE int checkSemiprime ( int num ) { int cnt = 0 ; for ( int i = 2 ; cnt < 2 && i * i <= num ; ++ i ) while ( num % i == 0 ) num /= i , ++ cnt ; if ( num > 1 ) ++ cnt ; return cnt == 2 ; } void semiprime ( int n ) { if ( checkSemiprime ( n ) ) printf ( " True STRNEWLINE " ) ; else printf ( " False STRNEWLINE " ) ; } int main ( ) { int n = 6 ; semiprime ( n ) ; n = 8 ; semiprime ( n ) ; return 0 ; }
Reverse Level Order Traversal | A recursive C program to print REVERSE level order traversal ; A binary tree node has data , pointer to left and right child ; Function protoypes ; Function to print REVERSE level order traversal a tree ; Print nodes at a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; Let us create trees shown in above diagram
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; void printGivenLevel ( struct node * root , int level ) ; int height ( struct node * node ) ; struct node * newNode ( int data ) ; void reverseLevelOrder ( struct node * root ) { int h = height ( root ) ; int i ; for ( i = h ; i >= 1 ; i -- ) printGivenLevel ( root , i ) ; } void printGivenLevel ( struct node * root , int level ) { if ( root == NULL ) return ; if ( level == 1 ) printf ( " % d ▁ " , root -> data ) ; else if ( level > 1 ) { printGivenLevel ( root -> left , level - 1 ) ; printGivenLevel ( root -> right , level - 1 ) ; } } int height ( struct node * node ) { if ( node == NULL ) return 0 ; else { int lheight = height ( node -> left ) ; int rheight = height ( node -> right ) ; if ( lheight > rheight ) return ( lheight + 1 ) ; else return ( rheight + 1 ) ; } } 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 ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; printf ( " Level ▁ Order ▁ traversal ▁ of ▁ binary ▁ tree ▁ is ▁ STRNEWLINE " ) ; reverseLevelOrder ( root ) ; return 0 ; }
Indexed Sequential Search | C program for Indexed Sequential Search ; Storing element ; Storing the index ; Driver code ; Element to search ; Function call
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void indexedSequentialSearch ( int arr [ ] , int n , int k ) { int elements [ 20 ] , indices [ 20 ] , temp , i , set = 0 ; int j = 0 , ind = 0 , start , end ; for ( i = 0 ; i < n ; i += 3 ) { elements [ ind ] = arr [ i ] ; indices [ ind ] = i ; ind ++ ; } if ( k < elements [ 0 ] ) { printf ( " Not ▁ found " ) ; exit ( 0 ) ; } else { for ( i = 1 ; i <= ind ; i ++ ) if ( k <= elements [ i ] ) { start = indices [ i - 1 ] ; end = indices [ i ] ; set = 1 ; break ; } } if ( set == 0 ) { start = indices [ i - 1 ] ; end = n ; } for ( i = start ; i <= end ; i ++ ) { if ( k == arr [ i ] ) { j = 1 ; break ; } } if ( j == 1 ) printf ( " Found ▁ at ▁ index ▁ % d " , i ) ; else printf ( " Not ▁ found " ) ; } void main ( ) { int arr [ ] = { 6 , 7 , 8 , 9 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 8 ; indexedSequentialSearch ( arr , n , k ) ; }
Next Smaller Element | Simple C program to print next smaller elements in a given array ; prints element and NSE pair for all elements of arr [ ] of size n ; Driver Code
#include <stdio.h> NEW_LINE void printNSE ( int arr [ ] , int n ) { int next , i , j ; for ( i = 0 ; i < n ; i ++ ) { next = -1 ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] > arr [ j ] ) { next = arr [ j ] ; break ; } } printf ( " % d ▁ - - ▁ % d STRNEWLINE " , arr [ i ] , next ) ; } } int main ( ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNSE ( arr , n ) ; return 0 ; }
MSD ( Most Significant Digit ) Radix Sort | C program for the implementation of MSD Radix Sort using counting sort ( ) ; A utility function to print an array ; A utility function to get the digit at index d in a integer ; function to sort array using MSD Radix Sort recursively ; recursion break condition ; temp is created to easily swap strings in arr [ ] ; Store occurrences of most significant character from each integer in count [ ] ; Change count [ ] so that count [ ] now contains actual position of this digits in temp [ ] ; Build the temp ; Copy all integer of temp to arr [ ] , so that arr [ ] now contains partially sorted integers ; Recursively MSD_sort ( ) on each partially sorted integers set to sort them by their next digit ; function find the largest integer ; Main function to call MSD_sort ; Find the maximum number to know number of digits ; get the length of the largest integer ; function call ; Driver Code ; Input array ; Size of the array ; Print the unsorted array ; Function Call ; Print the sorted array
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE void print ( int * arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { printf ( " % d , ▁ " , arr [ i ] ) ; } printf ( " STRNEWLINE " ) ; } int digit_at ( int x , int d ) { return ( int ) ( x / pow ( 10 , d - 1 ) ) % 10 ; } void MSD_sort ( int * arr , int lo , int hi , int d ) { if ( hi <= lo d < 1 ) { return ; } int count [ 10 + 2 ] = { 0 } ; int temp [ n ] ; for ( int i = lo ; i <= hi ; i ++ ) { int c = digit_at ( arr [ i ] , d ) ; count ++ ; } for ( int r = 0 ; r < 10 + 1 ; r ++ ) count [ r + 1 ] += count [ r ] ; for ( int i = lo ; i <= hi ; i ++ ) { int c = digit_at ( arr [ i ] , d ) ; temp [ count ++ ] = arr [ i ] ; } for ( int i = lo ; i <= hi ; i ++ ) { arr [ i ] = temp [ i - lo ] ; } for ( int r = 0 ; r < 10 ; r ++ ) MSD_sort ( arr , lo + count [ r ] , lo + count [ r + 1 ] - 1 , d - 1 ) ; } int getMax ( int arr [ ] , int n ) { int mx = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > mx ) mx = arr [ i ] ; return mx ; } void radixsort ( int * arr , int n ) { int m = getMax ( arr , n ) ; int d = floor ( log10 ( abs ( m ) ) ) + 1 ; MSD_sort ( arr , 0 , n - 1 , d ) ; } int main ( ) { int arr [ ] = { 9330 , 9950 , 718 , 8977 , 6790 , 95 , 9807 , 741 , 8586 , 5710 } ; n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Unsorted ▁ array ▁ : ▁ " ) ; print ( arr , n ) ; radixsort ( arr , n ) ; printf ( " Sorted ▁ array ▁ : ▁ " ) ; print ( arr , n ) ; return 0 ; }
In | Merge In Place in C ; Both sorted sub - arrays must be adjacent in ' a ' ' an ' is the length of the first sorted section in ' a ' ' bn ' is the length of the second sorted section in ' a ' ; Return right now if we 're done ; Do insertion sort to merge if size of sub - arrays are small enough ; p -- ) Insert Sort A into B ; p ++ ) Insert Sort B into A ; Find the pivot points . Basically this is just finding the point in ' a ' where we can swap in the first part of ' b ' such that after the swap the last element in ' a ' will be less than or equal to the least element in ' b ' ; Swap first part of b with last part of a ; Now merge the two sub - array pairings ; } merge_array_inplace ; Merge Sort Implementation ; Sort first and second halves ; Now merge the two sorted sub - arrays together ; Function to print an array ; Driver program to test sort utiliyy
#include <stddef.h> NEW_LINE #include <stdio.h> NEW_LINE #define __INSERT_THRESH 5 NEW_LINE #define __swap ( x , y ) (t = *(x), *(x) = *(y), *(y) = t) NEW_LINE static void merge ( int * a , size_t an , size_t bn ) { int * b = a + an , * e = b + bn , * s , t ; if ( an == 0 || bn == 0 || ! ( * b < * ( b - 1 ) ) ) return ; if ( an < __INSERT_THRESH && an <= bn ) { for ( int * p = b , * v ; p > a ; for ( v = p , s = p - 1 ; v < e && * v < * s ; s = v , v ++ ) __swap ( s , v ) ; return ; } if ( bn < __INSERT_THRESH ) { for ( int * p = b , * v ; p < e ; for ( s = p , v = p - 1 ; s > a && * s < * v ; s = v , v -- ) __swap ( s , v ) ; return ; } int * pa = a , * pb = b ; for ( s = a ; s < b && pb < e ; s ++ ) if ( * pb < * pa ) pb ++ ; else pa ++ ; pa += b - s ; for ( int * la = pa , * fb = b ; la < b ; la ++ , fb ++ ) __swap ( la , fb ) ; merge ( a , pa - a , pb - b ) ; merge ( b , pb - b , e - pb ) ; #undef __swap #undef __INSERT_THRESH void merge_sort ( int * a , size_t n ) { size_t m = ( n + 1 ) / 2 ; if ( m > 1 ) merge_sort ( a , m ) ; if ( n - m > 1 ) merge_sort ( a + m , n - m ) ; merge ( a , m , n - m ) ; } void print_array ( int a [ ] , size_t n ) { if ( n > 0 ) { printf ( " % d " , a [ 0 ] ) ; for ( size_t i = 1 ; i < n ; i ++ ) printf ( " ▁ % d " , a [ i ] ) ; } printf ( " STRNEWLINE " ) ; } int main ( ) { int a [ ] = { 3 , 16 , 5 , 14 , 8 , 10 , 7 , 15 , 1 , 13 , 4 , 9 , 12 , 11 , 6 , 2 } ; size_t n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; merge_sort ( a , n ) ; print_array ( a , n ) ; return 0 ; }
Channel Assignment Problem | ; A Depth First Search based recursive function that returns true if a matching for vertex u is possible ; Try every receiver one by one ; If sender u has packets to send to receiver v and receiver v is not already mapped to any other sender just check if the number of packets is greater than '0' because only one packet can be sent in a time frame anyways ; Mark v as visited ; If receiver ' v ' is not assigned to any sender OR previously assigned sender for receiver v ( which is matchR [ v ] ) has an alternate receiver available . Since v is marked as visited in the above line , matchR [ v ] in the following recursive call will not get receiver ' v ' again ; Returns maximum number of packets that can be sent parallely in 1 time slot from sender to receiver ; An array to keep track of the receivers assigned to the senders . The value of matchR [ i ] is the sender ID assigned to receiver i . the value - 1 indicates nobody is assigned . ; Initially all receivers are not mapped to any senders ; Count of receivers assigned to senders ; Mark all receivers as not seen for next sender ; Find if the sender ' u ' can be assigned to the receiver ; Driver program to test above function
#include <iostream> NEW_LINE #include <string.h> NEW_LINE #include <vector> NEW_LINE #define M 3 NEW_LINE #define N 4 NEW_LINE using namespace std ; bool bpm ( int table [ M ] [ N ] , int u , bool seen [ ] , int matchR [ ] ) { for ( int v = 0 ; v < N ; v ++ ) { if ( table [ u ] [ v ] > 0 && ! seen [ v ] ) { seen [ v ] = true ; if ( matchR [ v ] < 0 || bpm ( table , matchR [ v ] , seen , matchR ) ) { matchR [ v ] = u ; return true ; } } } return false ; } int maxBPM ( int table [ M ] [ N ] ) { int matchR [ N ] ; memset ( matchR , -1 , sizeof ( matchR ) ) ; int result = 0 ; for ( int u = 0 ; u < M ; u ++ ) { bool seen [ N ] ; memset ( seen , 0 , sizeof ( seen ) ) ; if ( bpm ( table , u , seen , matchR ) ) result ++ ; } cout << " The ▁ number ▁ of ▁ maximum ▁ packets ▁ sent ▁ in ▁ the ▁ time ▁ slot ▁ is ▁ " << result << " STRNEWLINE " ; for ( int x = 0 ; x < N ; x ++ ) if ( matchR [ x ] + 1 != 0 ) cout << " T " << matchR [ x ] + 1 << " - > ▁ R " << x + 1 << " STRNEWLINE " ; return result ; } int main ( ) { int table [ M ] [ N ] = { { 0 , 2 , 0 } , { 3 , 0 , 1 } , { 2 , 4 , 0 } } ; int max_flow = maxBPM ( table ) ; return 0 ; }
Decode an Encoded Base 64 String to ASCII String | C Program to decode a base64 Encoded string back to ASCII string ; char_set = " ABCDEFGHIJKLMNOPQRSTUVWXYZ ▁ abcdefghijklmnopqrstuvwxyz0123456789 + / " ; stores the bitstream . ; count_bits stores current number of bits in num . ; selects 4 characters from encoded string at a time . find the position of each encoded character in char_set and stores in num . ; make space for 6 bits . ; encoded [ i + j ] = ' E ' , ' E ' - ' A ' = 5 ' E ' has 5 th position in char_set . ; encoded [ i + j ] = ' e ' , ' e ' - ' a ' = 5 , 5 + 26 = 31 , ' e ' has 31 st position in char_set . ; encoded [ i + j ] = '8' , '8' - '0' = 8 8 + 52 = 60 , '8' has 60 th position in char_set . ; ' + ' occurs in 62 nd position in char_set . ; ' / ' occurs in 63 rd position in char_set . ; ( str [ i + j ] == ' = ' ) remove 2 bits to delete appended bits during encoding . ; 255 in binary is 11111111 ; Driver function ; Do not count last NULL character .
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define SIZE 100 NEW_LINE char * base64Decoder ( char encoded [ ] , int len_str ) { char * decoded_string ; decoded_string = ( char * ) malloc ( sizeof ( char ) * SIZE ) ; int i , j , k = 0 ; int num = 0 ; int count_bits = 0 ; for ( i = 0 ; i < len_str ; i += 4 ) { num = 0 , count_bits = 0 ; for ( j = 0 ; j < 4 ; j ++ ) { if ( encoded [ i + j ] != ' = ' ) { num = num << 6 ; count_bits += 6 ; } if ( encoded [ i + j ] >= ' A ' && encoded [ i + j ] <= ' Z ' ) num = num | ( encoded [ i + j ] - ' A ' ) ; else if ( encoded [ i + j ] >= ' a ' && encoded [ i + j ] <= ' z ' ) num = num | ( encoded [ i + j ] - ' a ' + 26 ) ; else if ( encoded [ i + j ] >= '0' && encoded [ i + j ] <= '9' ) num = num | ( encoded [ i + j ] - '0' + 52 ) ; else if ( encoded [ i + j ] == ' + ' ) num = num | 62 ; else if ( encoded [ i + j ] == ' / ' ) num = num | 63 ; else { num = num >> 2 ; count_bits -= 2 ; } } while ( count_bits != 0 ) { count_bits -= 8 ; decoded_string [ k ++ ] = ( num >> count_bits ) & 255 ; } } decoded_string [ k ] = ' \0' ; return decoded_string ; } int main ( ) { char encoded_string [ ] = " TUVOT04 = " ; int len_str = sizeof ( encoded_string ) / sizeof ( encoded_string [ 0 ] ) ; len_str -= 1 ; printf ( " Encoded ▁ string ▁ : ▁ % s STRNEWLINE " , encoded_string ) ; printf ( " Decoded _ string ▁ : ▁ % s STRNEWLINE " , base64Decoder ( encoded_string , len_str ) ) ; return 0 ; }
Print list items containing all characters of a given word | C program to print all strings that contain all characters of a word ; prints list items having all characters of word ; Since calloc is used , map [ ] is initialized as 0 ; Set the values in map ; Get the length of given word ; Check each item of list if has all characters of word ; unset the bit so that strings like sss not printed ; Set the values in map for next item ; Driver program to test to pront printDups
# include <stdio.h> NEW_LINE # include <stdlib.h> NEW_LINE # include <string.h> NEW_LINE # define NO_OF_CHARS 256 NEW_LINE void print ( char * list [ ] , char * word , int list_size ) { int * map = ( int * ) calloc ( sizeof ( int ) , NO_OF_CHARS ) ; int i , j , count , word_size ; for ( i = 0 ; * ( word + i ) ; i ++ ) map [ * ( word + i ) ] = 1 ; word_size = strlen ( word ) ; for ( i = 0 ; i < list_size ; i ++ ) { for ( j = 0 , count = 0 ; * ( list [ i ] + j ) ; j ++ ) { if ( map [ * ( list [ i ] + j ) ] ) { count ++ ; map [ * ( list [ i ] + j ) ] = 0 ; } } if ( count == word_size ) printf ( " % s " , list [ i ] ) ; for ( j = 0 ; * ( word + j ) ; j ++ ) map [ * ( word + j ) ] = 1 ; } } int main ( ) { char str [ ] = " sun " ; char * list [ ] = { " geeksforgeeks " , " unsorted " , " sunday " , " just " , " sss " } ; print ( list , str , 5 ) ; getchar ( ) ; return 0 ; }
Given a string , find its first non | C program to find first non - repeating character ; Returns an array of size 256 containing count of characters in the passed char array ; The function returns index of first non - repeating character in a string . If all characters are repeating then returns - 1 ; To avoid memory leak ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define NO_OF_CHARS 256 NEW_LINE int * getCharCountArray ( char * str ) { int * count = ( int * ) calloc ( sizeof ( int ) , NO_OF_CHARS ) ; int i ; for ( i = 0 ; * ( str + i ) ; i ++ ) count [ * ( str + i ) ] ++ ; return count ; } int firstNonRepeating ( char * str ) { int * count = getCharCountArray ( str ) ; int index = -1 , i ; for ( i = 0 ; * ( str + i ) ; i ++ ) { if ( count [ * ( str + i ) ] == 1 ) { index = i ; break ; } } free ( count ) ; return index ; } int main ( ) { char str [ ] = " geeksforgeeks " ; int index = firstNonRepeating ( str ) ; if ( index == -1 ) printf ( " Either ▁ all ▁ characters ▁ are ▁ repeating ▁ or ▁ " " string ▁ is ▁ empty " ) ; else printf ( " First ▁ non - repeating ▁ character ▁ is ▁ % c " , str [ index ] ) ; getchar ( ) ; return 0 ; }
Divide a string in N equal parts | C program to divide a string in n equal parts ; Function to print n equal parts of str ; Check if string can be divided in n equal parts ; Calculate the size of parts to find the division points ; length od string is 28 ; Print 4 equal parts of the string
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE void divideString ( char * str , int n ) { int str_size = strlen ( str ) ; int i ; int part_size ; if ( str_size % n != 0 ) { printf ( " Invalid ▁ Input : ▁ String ▁ size " ) ; printf ( " ▁ is ▁ not ▁ divisible ▁ by ▁ n " ) ; return ; } part_size = str_size / n ; for ( i = 0 ; i < str_size ; i ++ ) { if ( i % part_size == 0 ) printf ( " STRNEWLINE " ) ; printf ( " % c " , str [ i ] ) ; } } int main ( ) { char * str = " a _ simple _ divide _ string _ quest " ; divideString ( str , 4 ) ; getchar ( ) ; return 0 ; }
Program to check if three points are collinear | Slope based solution to check if three points are collinear . ; function to check if point collinear or not ; Driver Code
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE void collinear ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 ) { if ( ( y3 - y2 ) * ( x2 - x1 ) == ( y2 - y1 ) * ( x3 - x2 ) ) printf ( " Yes " ) ; else printf ( " No " ) ; } int main ( ) { int x1 = 1 , x2 = 1 , x3 = 0 , y1 = 1 , y2 = 6 , y3 = 9 ; collinear ( x1 , y1 , x2 , y2 , x3 , y3 ) ; return 0 ; }
Represent a given set of points by the best possible straight line | C Program to find m and c for a straight line given , x and y ; function to calculate m and c that best fit points represented by x [ ] and y [ ] ; Driver main function
#include <stdio.h> NEW_LINE void bestApproximate ( int x [ ] , int y [ ] , int n ) { int i , j ; float m , c , sum_x = 0 , sum_y = 0 , sum_xy = 0 , sum_x2 = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum_x += x [ i ] ; sum_y += y [ i ] ; sum_xy += x [ i ] * y [ i ] ; sum_x2 += ( x [ i ] * x [ i ] ) ; } m = ( n * sum_xy - sum_x * sum_y ) / ( n * sum_x2 - ( sum_x * sum_x ) ) ; c = ( sum_y - m * sum_x ) / n ; printf ( " m ▁ = % ▁ f " , m ) ; printf ( " c = % f " , c ) ; } int main ( ) { int x [ ] = { 1 , 2 , 3 , 4 , 5 } ; int y [ ] = { 14 , 27 , 40 , 55 , 68 } ; int n = sizeof ( x ) / sizeof ( x [ 0 ] ) ; bestApproximate ( x , y , n ) ; return 0 ; }
Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which subrpoblem ( s ) to call ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE #include <string.h> NEW_LINE int min ( int a , int b ) { return a < b ? a : b ; } int findMinInsertions ( char str [ ] , int l , int h ) { if ( l > h ) return INT_MAX ; if ( l == h ) return 0 ; if ( l == h - 1 ) return ( str [ l ] == str [ h ] ) ? 0 : 1 ; return ( str [ l ] == str [ h ] ) ? findMinInsertions ( str , l + 1 , h - 1 ) : ( min ( findMinInsertions ( str , l , h - 1 ) , findMinInsertions ( str , l + 1 , h ) ) + 1 ) ; } int main ( ) { char str [ ] = " geeks " ; printf ( " % d " , findMinInsertions ( str , 0 , strlen ( str ) - 1 ) ) ; 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 <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left , * 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 ; } void morrisTraversalPreorder ( struct node * root ) { while ( root ) { if ( root -> left == NULL ) { printf ( " % d ▁ " , root -> data ) ; root = root -> right ; } else { struct node * current = root -> left ; while ( current -> right && current -> right != root ) current = current -> right ; if ( current -> right == root ) { current -> right = NULL ; root = root -> right ; } else { printf ( " % d ▁ " , root -> data ) ; current -> right = root ; root = root -> left ; } } } } void preorder ( struct node * root ) { if ( root ) { printf ( " % d ▁ " , root -> data ) ; preorder ( root -> left ) ; preorder ( root -> right ) ; } } int main ( ) { struct 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 ) ; printf ( " STRNEWLINE " ) ; preorder ( root ) ; 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 ( 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 ; }
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 ( struct Node * prev_node , int new_data ) { if ( prev_node == NULL ) { printf ( " the ▁ given ▁ previous ▁ node ▁ cannot ▁ be ▁ NULL " ) ; return ; } struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = prev_node -> next ; prev_node -> next = new_node ; }
Program for n 'th node from the end of a Linked List |
void printNthFromLast ( struct Node * head , int n ) { static int i = 0 ; if ( head == NULL ) return ; printNthFromLast ( head -> next , n ) ; if ( ++ i == n ) printf ( " % d " , head -> data ) ; }
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 program to test above function ; Start with the empty list ; Create a loop for testing
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ; } int detectLoop ( struct Node * list ) { struct 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 ( ) { 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 ) ) printf ( " Loop ▁ found " ) ; else printf ( " No ▁ Loop " ) ; return 0 ; }
Function to check if a singly linked list is palindrome | Program to check if a linked list is palindrome ; Link list node ; Function to check if given linked list is palindrome or not ; To handle odd size list ; initialize result ; Get the middle of the list . Move slow_ptr by 1 and fast_ptrr by 2 , slow_ptr will have the middle node ; We need previous of the slow_ptr for linked lists with odd elements ; fast_ptr would become NULL when there are even elements in list . And not NULL for odd elements . We need to skip the middle node for odd case and store it somewhere so that we can restore the original list ; Now reverse the second half and compare it with first half ; NULL terminate first half ; Reverse the second half ; compare ; Reverse the second half again ; If there was a mid node ( odd size case ) which was not part of either first half or second half . ; Function to reverse the linked list Note that this function may change the head ; Function to check if two input lists have same data ; Both are empty reurn 1 ; Will reach here when one is NULL and other is not ; Push a node to linked list . Note that this function changes the head ; allocate node ; link the old list off the new node ; move the head to pochar to the new node ; A utility function to print a given linked list ; Drier program to test above function ; Start with the empty list
#include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { char data ; struct Node * next ; } ; void reverse ( struct Node * * ) ; bool compareLists ( struct Node * , struct Node * ) ; bool isPalindrome ( struct Node * head ) { struct Node * slow_ptr = head , * fast_ptr = head ; struct Node * second_half , * prev_of_slow_ptr = head ; struct Node * midnode = NULL ; bool res = true ; if ( head != NULL && head -> next != NULL ) { while ( fast_ptr != NULL && fast_ptr -> next != NULL ) { fast_ptr = fast_ptr -> next -> next ; prev_of_slow_ptr = slow_ptr ; slow_ptr = slow_ptr -> next ; } if ( fast_ptr != NULL ) { midnode = slow_ptr ; slow_ptr = slow_ptr -> next ; } second_half = slow_ptr ; prev_of_slow_ptr -> next = NULL ; reverse ( & second_half ) ; res = compareLists ( head , second_half ) ; reverse ( & second_half ) ; if ( midnode != NULL ) { prev_of_slow_ptr -> next = midnode ; midnode -> next = second_half ; } else prev_of_slow_ptr -> next = second_half ; } return res ; } void reverse ( struct Node * * head_ref ) { struct Node * prev = NULL ; struct Node * current = * head_ref ; struct Node * next ; while ( current != NULL ) { next = current -> next ; current -> next = prev ; prev = current ; current = next ; } * head_ref = prev ; } bool compareLists ( struct Node * head1 , struct Node * head2 ) { struct Node * temp1 = head1 ; struct Node * temp2 = head2 ; while ( temp1 && temp2 ) { if ( temp1 -> data == temp2 -> data ) { temp1 = temp1 -> next ; temp2 = temp2 -> next ; } else return 0 ; } if ( temp1 == NULL && temp2 == NULL ) return 1 ; return 0 ; } void push ( struct Node * * head_ref , char 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 * ptr ) { while ( ptr != NULL ) { printf ( " % c - > " , ptr -> data ) ; ptr = ptr -> next ; } printf ( " NULL STRNEWLINE " ) ; } int main ( ) { struct Node * head = NULL ; char str [ ] = " abacaba " ; int i ; for ( i = 0 ; str [ i ] != ' \0' ; i ++ ) { push ( & head , str [ i ] ) ; printList ( head ) ; isPalindrome ( head ) ? printf ( " Is ▁ Palindrome STRNEWLINE STRNEWLINE " ) : printf ( " Not ▁ Palindrome STRNEWLINE STRNEWLINE " ) ; } 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 <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; void swapNodes ( struct Node * * head_ref , int x , int y ) { if ( x == y ) return ; struct Node * prevX = NULL , * currX = * head_ref ; while ( currX && currX -> data != x ) { prevX = currX ; currX = currX -> next ; } struct 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 ; struct Node * temp = currY -> next ; currY -> next = currX -> next ; currX -> next = temp ; } 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 ) { printf ( " % d ▁ " , node -> data ) ; node = node -> next ; } } int main ( ) { struct Node * start = NULL ; push ( & start , 7 ) ; push ( & start , 6 ) ; push ( & start , 5 ) ; push ( & start , 4 ) ; push ( & start , 3 ) ; push ( & start , 2 ) ; push ( & start , 1 ) ; printf ( " Linked list before calling swapNodes ( ) " printList ( start ) ; swapNodes ( & start , 4 , 3 ) ; printf ( " Linked list after calling swapNodes ( ) " printList ( start ) ; return 0 ; }
Pairwise swap elements of a given linked list | Recursive function to pairwise swap elements of a linked list ; There must be at - least two nodes in the list ; Swap the node 's data with data of next node ; Call pairWiseSwap ( ) for rest of the list
void pairWiseSwap ( struct node * head ) { if ( head != NULL && head -> next != NULL ) { swap ( & head -> data , & head -> next -> data ) ; pairWiseSwap ( head -> next -> next ) ; } }
Sorted insert for circular linked list | Case 2 of the above algo ; swap the data part of head node and new node assuming that we have a function swap ( int * , int * )
else if ( current -> data >= new_node -> data ) { swap ( & ( current -> data ) , & ( new_node -> data ) ) ; new_node -> next = ( * head_ref ) -> next ; ( * head_ref ) -> next = new_node ; }
Doubly Linked List | Set 1 ( Introduction and Insertion ) | 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. allocate node * 2. put in the data ; 3. Make next of new node as head and previous as NULL ; 4. change prev of head node to new node ; 5. move the head to point to the new node
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 ) ; new_node -> prev = NULL ; if ( ( * head_ref ) != NULL ) ( * head_ref ) -> prev = new_node ; ( * head_ref ) = new_node ; }
Doubly Linked List | Set 1 ( Introduction and Insertion ) | Given a node as prev_node , insert a new node after the given node ; 1. check if the given prev_node is NULL ; 2. allocate node * 3. put in the data ; 4. Make next of new node as next of prev_node ; 5. Make the next of prev_node as new_node ; 6. Make prev_node as previous of new_node ; 7. Change previous of new_node 's next node
void insertAfter ( struct Node * prev_node , int new_data ) { if ( prev_node == NULL ) { printf ( " the ▁ given ▁ previous ▁ node ▁ cannot ▁ be ▁ NULL " ) ; return ; } struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = prev_node -> next ; prev_node -> next = new_node ; new_node -> prev = prev_node ; if ( new_node -> next != NULL ) new_node -> next -> prev = new_node ; }
Doubly Linked List | Set 1 ( Introduction and Insertion ) | Given a reference ( pointer to pointer ) to the head of a DLL and an int , appends a new node at the end ; 1. allocate node 2. put in the data ; 3. This new node is going to be the last node , so make next of it as NULL ; 4. If the Linked List is empty , then make the new node as head ; 5. Else traverse till the last node ; 6. Change the next of last node ; 7. Make last node as previous of new node
void append ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * last = * head_ref ; new_node -> data = new_data ; new_node -> next = NULL ; if ( * head_ref == NULL ) { new_node -> prev = NULL ; * head_ref = new_node ; return ; } while ( last -> next != NULL ) last = last -> next ; last -> next = new_node ; new_node -> prev = last ; return ; }
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 <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { struct Node * prev ; int info ; struct Node * next ; } ; void nodeInsetail ( struct Node * * head , struct Node * * tail , int key ) { struct 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 ; } 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 ( struct Node * temp ) { while ( temp != NULL ) { printf ( " % d ▁ " , temp -> info ) ; temp = temp -> next ; } } int main ( ) { struct 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 ) ; printf ( " Doubly linked list on printing " ▁ " from left to right " printList ( left ) ; 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 ) ; printf ( " % d ▁ " , head -> data ) ; }
Practice questions for Linked List and Recursion |
void fun2 ( struct Node * head ) { if ( head == NULL ) return ; printf ( " % d ▁ " , head -> data ) ; if ( head -> next != NULL ) fun2 ( head -> next -> next ) ; printf ( " % d ▁ " , 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 program to test above functions ; Start with the empty list ; Using push ( ) to construct below list 1 -> 2 -> 3 -> 4 -> 5
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; void fun1 ( struct Node * head ) { if ( head == NULL ) return ; fun1 ( head -> next ) ; printf ( " % d ▁ " , head -> data ) ; } void fun2 ( struct Node * start ) { if ( start == NULL ) return ; printf ( " % d ▁ " , start -> data ) ; if ( start -> next != NULL ) fun2 ( start -> next -> next ) ; printf ( " % d ▁ " , start -> data ) ; } 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 main ( ) { struct Node * head = NULL ; push ( & head , 5 ) ; push ( & head , 4 ) ; push ( & head , 3 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; printf ( " Output ▁ of ▁ fun1 ( ) ▁ for ▁ list ▁ 1 - > 2 - > 3 - > 4 - > 5 ▁ STRNEWLINE " ) ; fun1 ( head ) ; printf ( " Output of fun2 ( ) for list 1 -> 2 -> 3 -> 4 -> 5 " fun2 ( head ) ; getchar ( ) ; return 0 ; }
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 <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; int printsqrtn ( struct Node * head ) { struct 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 ( struct Node * head ) { while ( head != NULL ) { printf ( " % d ▁ " , head -> data ) ; head = head -> next ; } printf ( " STRNEWLINE " ) ; } 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 main ( ) { struct Node * head = NULL ; push ( & head , 40 ) ; push ( & head , 30 ) ; push ( & head , 20 ) ; push ( & head , 10 ) ; printf ( " Given ▁ linked ▁ list ▁ is : " ) ; print ( head ) ; printf ( " sqrt ( n ) th ▁ node ▁ is ▁ % d ▁ " , printsqrtn ( head ) ) ; return 0 ; }
Find the node with minimum value in a 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 program to test sameTree function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ) ; printf ( " Minimum value in BST is % d " , minValue ( root ) ) ; getchar ( ) ; return 0 ; }
Construct Tree from given Inorder and Preorder traversals | 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 program to test above functions ; Let us test the built tree by printing Insorder traversal
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { char data ; struct node * left ; struct node * right ; } ; int search ( char arr [ ] , int strt , int end , char value ) ; struct node * newNode ( char data ) ; struct node * buildTree ( char in [ ] , char pre [ ] , int inStrt , int inEnd ) { static int preIndex = 0 ; if ( inStrt > inEnd ) return NULL ; struct 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 ; } } struct node * newNode ( char data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } 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 = buildTree ( in , pre , 0 , len - 1 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree ▁ is ▁ STRNEWLINE " ) ; printInorder ( root ) ; getchar ( ) ; }
Lowest Common Ancestor in a Binary Search Tree . | A recursive C 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 program to test lca ( ) ; Let us construct the BST shown in the above figure
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct 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 ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( ) { struct 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 ; struct node * t = lca ( root , n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , n1 , n2 , t -> data ) ; n1 = 14 , n2 = 8 ; t = lca ( root , n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , n1 , n2 , t -> data ) ; n1 = 10 , n2 = 22 ; t = lca ( root , n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , n1 , n2 , t -> data ) ; getchar ( ) ; 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 ; }
Check if each internal node of a BST has exactly one child | Check if each internal node of BST has only one child ; driver program to test above function
#include <stdio.h> NEW_LINE bool hasOnlyOneChild ( int pre [ ] , int size ) { int nextDiff , lastDiff ; for ( int i = 0 ; i < size - 1 ; i ++ ) { nextDiff = pre [ i ] - pre [ i + 1 ] ; lastDiff = pre [ i ] - pre [ size - 1 ] ; if ( nextDiff * lastDiff < 0 ) return false ; ; } return true ; } int main ( ) { int pre [ ] = { 8 , 3 , 5 , 7 , 6 } ; int size = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; if ( hasOnlyOneChild ( pre , size ) == true ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
Check if each internal node of a BST has exactly one child | Check if each internal node of BST has only one child ; Initialize min and max using last two elements ; Every element must be either smaller than min or greater than max ; Driver program to test above function
#include <stdio.h> NEW_LINE int hasOnlyOneChild ( int pre [ ] , int size ) { int min , max ; if ( pre [ size - 1 ] > pre [ size - 2 ] ) { max = pre [ size - 1 ] ; min = pre [ size - 2 ] ) : else { max = pre [ size - 2 ] ; min = pre [ size - 1 ] ; } for ( int i = size - 3 ; i >= 0 ; i -- ) { if ( pre [ i ] < min ) min = pre [ i ] ; else if ( pre [ i ] > max ) max = pre [ i ] ; else return false ; } return true ; } int main ( ) { int pre [ ] = { 8 , 3 , 5 , 7 , 6 } ; int size = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; if ( hasOnlyOneChild ( pre , size ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
AVL with duplicate keys | C ++ program of AVL tree that handles duplicates ; An AVL tree node ; A utility function to get maximum of two integers ; A utility function to get height of the tree ; A utility function to get maximum of two integers ; Helper function that allocates a new node with the given key and NULL left and right pointers . ; new node is initially added at leaf ; A utility function to right rotate subtree rooted with y See the diagram given above . ; Perform rotation ; Update heights ; Return new root ; A utility function to left rotate subtree rooted with x See the diagram given above . ; Perform rotation ; Update heights ; Return new root ; Get Balance factor of node N ; 1. Perform the normal BST rotation ; If key already exists in BST , increment count and return ; Otherwise , recur down the tree ; 2. Update height of this ancestor node ; 3. Get the balance factor of this ancestor node to check whether this node became unbalanced ; If this node becomes unbalanced , then there are 4 cases Left Left Case ; Right Right Case ; Left Right Case ; Right Left Case ; return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the node with minimum key value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; STEP 1 : PERFORM STANDARD BST DELETE ; If the key to be deleted is smaller than the root 's key, then it lies in left subtree ; If the key to be deleted is greater than the root 's key, then it lies in right subtree ; if key is same as root 's key, then This is the node to be deleted ; If key is present more than once , simply decrement count and return ; Else , delete the node node with only one child or no child ; No child case ; One child case ; Copy the contents of the non - empty child ; node with two children : Get the inorder successor ( smallest in the right subtree ) ; Copy the inorder successor 's data to this node and update the count ; Delete the inorder successor ; If the tree had only one node then return ; STEP 2 : UPDATE HEIGHT OF THE CURRENT NODE ; STEP 3 : GET THE BALANCE FACTOR OF THIS NODE ( to check whether this node became unbalanced ) ; If this node becomes unbalanced , then there are 4 cases Left Left Case ; Left Right Case ; Right Right Case ; Right Left Case ; A utility function to print preorder traversal of the tree . The function also prints height of every node ; Driver program to test above function ; Constructing tree given in the above figure
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int key ; struct node * left ; struct node * right ; int height ; int count ; } ; int max ( int a , int b ) ; int height ( struct node * N ) { if ( N == NULL ) return 0 ; return N -> height ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } struct node * newNode ( int key ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> key = key ; node -> left = NULL ; node -> right = NULL ; node -> height = 1 ; node -> count = 1 ; return ( node ) ; } struct node * rightRotate ( struct node * y ) { struct node * x = y -> left ; struct node * T2 = x -> right ; x -> right = y ; y -> left = T2 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; return x ; } struct node * leftRotate ( struct node * x ) { struct node * y = x -> right ; struct node * T2 = y -> left ; y -> left = x ; x -> right = T2 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; return y ; } int getBalance ( struct node * N ) { if ( N == NULL ) return 0 ; return height ( N -> left ) - height ( N -> right ) ; } struct node * insert ( struct node * node , int key ) { if ( node == NULL ) return ( newNode ( key ) ) ; if ( key == node -> key ) { ( node -> count ) ++ ; return node ; } if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else node -> right = insert ( node -> right , key ) ; node -> height = max ( height ( node -> left ) , height ( node -> right ) ) + 1 ; int balance = getBalance ( node ) ; if ( balance > 1 && key < node -> left -> key ) return rightRotate ( node ) ; if ( balance < -1 && key > node -> right -> key ) return leftRotate ( node ) ; if ( balance > 1 && key > node -> left -> key ) { node -> left = leftRotate ( node -> left ) ; return rightRotate ( node ) ; } if ( balance < -1 && key < node -> right -> key ) { node -> right = rightRotate ( node -> right ) ; return leftRotate ( node ) ; } return node ; } struct node * minValueNode ( struct node * node ) { struct node * current = node ; while ( current -> left != NULL ) current = current -> left ; return current ; } struct node * deleteNode ( struct node * root , int key ) { if ( root == NULL ) return root ; if ( key < root -> key ) root -> left = deleteNode ( root -> left , key ) ; else if ( key > root -> key ) root -> right = deleteNode ( root -> right , key ) ; else { if ( root -> count > 1 ) { ( root -> count ) -- ; return ; } if ( ( root -> left == NULL ) || ( root -> right == NULL ) ) { struct node * temp = root -> left ? root -> left : root -> right ; if ( temp == NULL ) { temp = root ; root = NULL ; } else * root = * temp ; free ( temp ) ; } else { struct node * temp = minValueNode ( root -> right ) ; root -> key = temp -> key ; root -> count = temp -> count ; temp -> count = 1 ; root -> right = deleteNode ( root -> right , temp -> key ) ; } } if ( root == NULL ) return root ; root -> height = max ( height ( root -> left ) , height ( root -> right ) ) + 1 ; int balance = getBalance ( root ) ; if ( balance > 1 && getBalance ( root -> left ) >= 0 ) return rightRotate ( root ) ; if ( balance > 1 && getBalance ( root -> left ) < 0 ) { root -> left = leftRotate ( root -> left ) ; return rightRotate ( root ) ; } if ( balance < -1 && getBalance ( root -> right ) <= 0 ) return leftRotate ( root ) ; if ( balance < -1 && getBalance ( root -> right ) > 0 ) { root -> right = rightRotate ( root -> right ) ; return leftRotate ( root ) ; } return root ; } void preOrder ( struct node * root ) { if ( root != NULL ) { printf ( " % d ( % d ) ▁ " , root -> key , root -> count ) ; preOrder ( root -> left ) ; preOrder ( root -> right ) ; } } int main ( ) { struct node * root = NULL ; root = insert ( root , 9 ) ; root = insert ( root , 5 ) ; root = insert ( root , 10 ) ; root = insert ( root , 5 ) ; root = insert ( root , 9 ) ; root = insert ( root , 7 ) ; root = insert ( root , 17 ) ; printf ( " Pre ▁ order ▁ traversal ▁ of ▁ the ▁ constructed ▁ AVL ▁ tree ▁ is ▁ STRNEWLINE " ) ; preOrder ( root ) ; root = deleteNode ( root , 9 ) ; printf ( " Pre order traversal after deletion of 9 " preOrder ( root ) ; return 0 ; }
Inorder Successor in Binary Search Tree | ; A binary tree node has data , the pointer to left child and a pointer to right child ; 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 ; step 1 of the above algorithm ; step 2 of the above algorithm ; 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 ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; struct node * parent ; } ; struct node * minValue ( struct node * node ) ; struct node * insert ( struct node * node , int data ) { if ( node == NULL ) return ( newNode ( data ) ) ; else { struct node * temp ; if ( data <= node -> data ) { temp = insert ( node -> left , data ) ; node -> left = temp ; temp -> parent = node ; } else { temp = insert ( node -> right , data ) ; node -> right = temp ; temp -> parent = node ; } return node ; } } struct node * inOrderSuccessor ( struct node * root , struct node * n ) { if ( n -> right != NULL ) return minValue ( n -> right ) ; struct node * p = n -> parent ; while ( p != NULL && n == p -> right ) { n = p ; p = p -> parent ; } return p ; } struct node * minValue ( struct node * node ) { struct node * current = node ; while ( current -> left != NULL ) { current = current -> left ; } return current ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; node -> parent = NULL ; return ( node ) ; } int main ( ) { struct node * root = NULL , * temp , * succ , * min ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 22 ) ; root = insert ( root , 4 ) ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 14 ) ; temp = root -> left -> right -> right ; succ = inOrderSuccessor ( root , temp ) ; if ( succ != NULL ) printf ( " Inorder Successor of % d is % d " , temp -> data , succ -> data ) ; else printf ( " Inorder Successor doesn ' exit " getchar ( ) ; 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 program to test above functions
#include <stdio.h> NEW_LINE struct node { int key ; struct node * left ; struct 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 ) ) printf ( " Present " ) ; else printf ( " 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 <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define MAX_SIZE 100 NEW_LINE struct node { int val ; struct node * left , * right ; } ; struct Stack { int size ; int top ; struct node * * array ; } ; struct Stack * createStack ( int size ) { struct Stack * stack = ( struct Stack * ) malloc ( sizeof ( struct Stack ) ) ; stack -> size = size ; stack -> top = -1 ; stack -> array = ( struct node * * ) malloc ( stack -> size * sizeof ( struct node * ) ) ; return stack ; } int isFull ( struct Stack * stack ) { return stack -> top - 1 == stack -> size ; } int isEmpty ( struct Stack * stack ) { return stack -> top == -1 ; } void push ( struct Stack * stack , struct node * node ) { if ( isFull ( stack ) ) return ; stack -> array [ ++ stack -> top ] = node ; } struct node * pop ( struct Stack * stack ) { if ( isEmpty ( stack ) ) return NULL ; return stack -> array [ stack -> top -- ] ; } bool isPairPresent ( struct node * root , int target ) { struct Stack * s1 = createStack ( MAX_SIZE ) ; struct Stack * s2 = createStack ( MAX_SIZE ) ; bool done1 = false , done2 = false ; int val1 = 0 , val2 = 0 ; struct 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 ) { printf ( " Pair Found : % d + % d = % d " , val1 , val2 , target ) ; return true ; } else if ( ( val1 + val2 ) < target ) done1 = false ; else if ( ( val1 + val2 ) > target ) done2 = false ; if ( val1 >= val2 ) return false ; } } struct node * NewNode ( int val ) { struct node * tmp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; tmp -> val = val ; tmp -> right = tmp -> left = NULL ; return tmp ; } int main ( ) { struct 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 ) printf ( " No such values are found " getchar ( ) ; return 0 ; }
Left Leaning Red Black Tree ( Insertion ) | C program to implement insert operation in Red Black Tree . ; red == > true , black == > false ; New Node which is created is always red in color . ; utility function to rotate node anticlockwise . ; utility function to rotate node clockwise . ; utility function to check whether node is red in color or not . ; utility function to swap color of two nodes . ; insertion into Left Leaning Red Black Tree . ; Normal insertion code for any Binary Search tree . ; case 1. when right child is Red but left child is Black or doesn 't exist. ; left rotate the node to make it into valid structure . ; swap the colors as the child node should always be red ; case 2 when left child as well as left grand child in Red ; right rotate the current node to make it into a valid structure . ; case 3 when both left and right child are Red in color . ; invert the color of node as well it 's left and right child. ; change the color to black . ; Inorder traversal ; Driver function ; LLRB tree made after all insertions are made . 1. Nodes which have double INCOMING edge means that they are RED in color . 2. Nodes which have single INCOMING edge means that they are BLACK in color . root | 40 \ 20 50 / \ 10 30 25 ; to make sure that root remains black is color ; display the tree through inorder traversal .
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <stdbool.h> NEW_LINE typedef struct node { struct node * left , * right ; int data ; bool color ; } node ; node * createNode ( int data , bool color ) { node * myNode = ( node * ) malloc ( sizeof ( node ) ) ; myNode -> left = myNode -> right = NULL ; myNode -> data = data ; myNode -> color = true ; return myNode ; } node * rotateLeft ( node * myNode ) { printf ( " left ▁ rotation ! ! STRNEWLINE " ) ; node * child = myNode -> right ; node * childLeft = child -> left ; child -> left = myNode ; myNode -> right = childLeft ; return child ; } node * rotateRight ( node * myNode ) { printf ( " right ▁ rotation STRNEWLINE " ) ; node * child = myNode -> left ; node * childRight = child -> right ; child -> right = myNode ; myNode -> left = childRight ; return child ; } int isRed ( node * myNode ) { if ( myNode == NULL ) return 0 ; return ( myNode -> color == true ) ; } void swapColors ( node * node1 , node * node2 ) { bool temp = node1 -> color ; node1 -> color = node2 -> color ; node2 -> color = temp ; } node * insert ( node * myNode , int data ) { if ( myNode == NULL ) return createNode ( data , false ) ; if ( data < myNode -> data ) myNode -> left = insert ( myNode -> left , data ) ; else if ( data > myNode -> data ) myNode -> right = insert ( myNode -> right , data ) ; else return myNode ; if ( isRed ( myNode -> right ) && ! isRed ( myNode -> left ) ) { myNode = rotateLeft ( myNode ) ; swapColors ( myNode , myNode -> left ) ; } if ( isRed ( myNode -> left ) && isRed ( myNode -> left -> left ) ) { myNode = rotateRight ( myNode ) ; swapColors ( myNode , myNode -> right ) ; } if ( isRed ( myNode -> left ) && isRed ( myNode -> right ) ) { myNode -> color = ! myNode -> color ; myNode -> left -> color = false ; myNode -> right -> color = false ; } return myNode ; } void inorder ( node * node ) { if ( node ) { inorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; inorder ( node -> right ) ; } } int main ( ) { node * root = NULL ; root = insert ( root , 10 ) ; root -> color = false ; root = insert ( root , 20 ) ; root -> color = false ; root = insert ( root , 30 ) ; root -> color = false ; root = insert ( root , 40 ) ; root -> color = false ; root = insert ( root , 50 ) ; root -> color = false ; root = insert ( root , 25 ) ; root -> color = false ; inorder ( root ) ; return 0 ; }
Threaded Binary Tree | Utility function to find leftmost node in a tree rooted with n ; C code to do inorder traversal in a threaded binary tree ; If this node is a thread node , then go to inorder successor ; Else go to the leftmost child in right ; subtree
struct Node * leftMost ( struct Node * n ) { if ( n == NULL ) return NULL ; while ( n -> left != NULL ) n = n -> left ; return n ; } void inOrder ( struct Node * root ) { struct Node * cur = leftMost ( root ) ; while ( cur != NULL ) { printf ( " % d ▁ " , cur -> data ) ; if ( cur -> rightThread ) cur = cur -> right ; else cur = leftmost ( cur -> right ) ; } }
Construct Full Binary Tree from given preorder and postorder traversals | program for construction of full binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function to create a node ; A recursive function to construct Full from pre [ ] and post [ ] . preIndex is used to keep track of index in pre [ ] . l is low index and h is high index for the current subarray in post [ ] ; Base case ; The first node in preorder traversal is root . So take the node at preIndex from preorder and make it root , and increment preIndex ; If the current subarry has only one element , no need to recur ; Search the next element of pre [ ] in post [ ] ; Use the index of element found in postorder to divide postorder array in two parts . Left subtree and right subtree ; The main function to construct Full Binary Tree from given preorder and postorder traversals . This function mainly uses constructTreeUtil ( ) ; A utility function to print inorder traversal of a Binary Tree ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * 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 ; } struct node * constructTreeUtil ( int pre [ ] , int post [ ] , int * preIndex , int l , int h , int size ) { if ( * preIndex >= size l > h ) return NULL ; struct node * root = newNode ( pre [ * preIndex ] ) ; ++ * preIndex ; if ( l == h ) return root ; int i ; for ( i = l ; i <= h ; ++ i ) if ( pre [ * preIndex ] == post [ i ] ) break ; if ( i <= h ) { root -> left = constructTreeUtil ( pre , post , preIndex , l , i , size ) ; root -> right = constructTreeUtil ( pre , post , preIndex , i + 1 , h , size ) ; } return root ; } struct node * constructTree ( int pre [ ] , int post [ ] , int size ) { int preIndex = 0 ; return constructTreeUtil ( pre , post , & preIndex , 0 , size - 1 , size ) ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; printInorder ( node -> right ) ; } int main ( ) { int pre [ ] = { 1 , 2 , 4 , 8 , 9 , 5 , 3 , 6 , 7 } ; int post [ ] = { 8 , 9 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int size = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; struct node * root = constructTree ( pre , post , size ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree : ▁ STRNEWLINE " ) ; printInorder ( root ) ; return 0 ; }
Sorted order printing of a given array that represents a BST | C Code for Sorted order printing of a given array that represents a BST ; print left subtree ; print root ; print right subtree ; driver program to test above function
#include <stdio.h> NEW_LINE void printSorted ( int arr [ ] , int start , int end ) { if ( start > end ) return ; printSorted ( arr , start * 2 + 1 , end ) ; printf ( " % d ▁ " , arr [ start ] ) ; printSorted ( arr , start * 2 + 2 , end ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 5 , 1 , 3 } ; int arr_size = sizeof ( arr ) / sizeof ( int ) ; printSorted ( arr , 0 , arr_size - 1 ) ; getchar ( ) ; return 0 ; }
Floor and Ceil from a BST | Program to find ceil of a given value in BST ; A binary tree node has key , left child and right child ; Helper function that allocates a new node with the given key and NULL left and right pointers . ; Function to find ceil of a given input in BST . If input is more than the max key in BST , return - 1 ; Base case ; We found equal key ; If root 's key is smaller, ceil must be in right subtree ; Else , either left subtree or root has the ceil value ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int key ; struct node * left ; struct node * right ; } ; struct node * newNode ( int key ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> key = key ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int Ceil ( struct node * root , int input ) { if ( root == NULL ) return -1 ; if ( root -> key == input ) return root -> key ; if ( root -> key < input ) return Ceil ( root -> right , input ) ; int ceil = Ceil ( root -> left , input ) ; return ( ceil >= input ) ? ceil : root -> key ; } int main ( ) { struct node * root = newNode ( 8 ) ; root -> left = newNode ( 4 ) ; root -> right = newNode ( 12 ) ; root -> left -> left = newNode ( 2 ) ; root -> left -> right = newNode ( 6 ) ; root -> right -> left = newNode ( 10 ) ; root -> right -> right = newNode ( 14 ) ; for ( int i = 0 ; i < 16 ; i ++ ) printf ( " % d ▁ % d STRNEWLINE " , i , Ceil ( root , i ) ) ; return 0 ; }
How to handle duplicates in Binary Search Tree ? | C program to implement basic operations ( search , insert and delete ) on a BST that handles duplicates by storing count with every node ; A utility function to create a new BST node ; A utility function to do inorder traversal of BST ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; If key already exists in BST , icnrement count and return ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the node with minimum key value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; Given a binary search tree and a key , this function deletes a given key and returns root of modified tree ; base case ; If the key to be deleted is smaller than the root 's key, then it lies in left subtree ; If the key to be deleted is greater than the root 's key, then it lies in right subtree ; if key is same as root 's key ; If key is present more than once , simply decrement count and return ; ElSE , delete the node node with only one child or no child ; node with two children : Get the inorder successor ( smallest in the right subtree ) ; Copy the inorder successor 's content to this node ; Delete the inorder successor ; Driver Program to test above functions ; Let us create following BST 12 ( 3 ) / \ 10 ( 2 ) 20 ( 1 ) / \ 9 ( 1 ) 11 ( 1 )
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int key ; int count ; struct node * left , * right ; } ; struct node * newNode ( int item ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> key = item ; temp -> left = temp -> right = NULL ; temp -> count = 1 ; return temp ; } void inorder ( struct node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; printf ( " % d ( % d ) ▁ " , root -> key , root -> count ) ; inorder ( root -> right ) ; } } struct node * insert ( struct node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key == node -> key ) { ( node -> count ) ++ ; return node ; } if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else node -> right = insert ( node -> right , key ) ; return node ; } struct node * minValueNode ( struct node * node ) { struct node * current = node ; while ( current -> left != NULL ) current = current -> left ; return current ; } struct node * deleteNode ( struct node * root , int key ) { if ( root == NULL ) return root ; if ( key < root -> key ) root -> left = deleteNode ( root -> left , key ) ; else if ( key > root -> key ) root -> right = deleteNode ( root -> right , key ) ; else { if ( root -> count > 1 ) { ( root -> count ) -- ; return root ; } if ( root -> left == NULL ) { struct node * temp = root -> right ; free ( root ) ; return temp ; } else if ( root -> right == NULL ) { struct node * temp = root -> left ; free ( root ) ; return temp ; } struct node * temp = minValueNode ( root -> right ) ; root -> key = temp -> key ; root -> right = deleteNode ( root -> right , temp -> key ) ; } return root ; } int main ( ) { struct node * root = NULL ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 20 ) ; root = insert ( root , 9 ) ; root = insert ( root , 11 ) ; root = insert ( root , 10 ) ; root = insert ( root , 12 ) ; root = insert ( root , 12 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ given ▁ tree ▁ STRNEWLINE " ) ; inorder ( root ) ; printf ( " Delete 20 " root = deleteNode ( root , 20 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ STRNEWLINE " ) ; inorder ( root ) ; printf ( " Delete 12 " root = deleteNode ( root , 12 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ STRNEWLINE " ) ; inorder ( root ) ; printf ( " Delete 9 " root = deleteNode ( root , 9 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ STRNEWLINE " ) ; inorder ( root ) ; return 0 ; }
How to implement decrease key or change key in Binary Search Tree ? | C program to demonstrate decrease key operation on binary search tree ; A utility function to create a new BST node ; A utility function to do inorder traversal of BST ; 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 ; Given a non - empty binary search tree , return the node with minimum key value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; Given a binary search tree and a key , this function deletes the key and returns the new root ; base case ; If the key to be deleted is smaller than the root 's key, then it lies in left subtree ; If the key to be deleted is greater than the root 's key, then it lies in right subtree ; if key is same as root 's key, then This is the node to be deleted ; node with only one child or no child ; node with two children : Get the inorder successor ( smallest in the right subtree ) ; Copy the inorder successor 's content to this node ; Delete the inorder successor ; Function to decrease a key value in Binary Search Tree ; First delete old key value ; Then insert new key value ; Return new root ; Driver Program to test above functions ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 ; BST is modified to 50 / \ 30 70 / / \ 20 60 80 / 10
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int key ; struct node * left , * right ; } ; struct node * newNode ( int item ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> key = item ; temp -> left = temp -> right = NULL ; return temp ; } void inorder ( struct node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; printf ( " % d ▁ " , root -> key ) ; inorder ( root -> right ) ; } } struct node * insert ( struct 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 ; } struct node * minValueNode ( struct node * node ) { struct node * current = node ; while ( current -> left != NULL ) current = current -> left ; return current ; } struct node * deleteNode ( struct node * root , int key ) { if ( root == NULL ) return root ; if ( key < root -> key ) root -> left = deleteNode ( root -> left , key ) ; else if ( key > root -> key ) root -> right = deleteNode ( root -> right , key ) ; else { if ( root -> left == NULL ) { struct node * temp = root -> right ; free ( root ) ; return temp ; } else if ( root -> right == NULL ) { struct node * temp = root -> left ; free ( root ) ; return temp ; } struct node * temp = minValueNode ( root -> right ) ; root -> key = temp -> key ; root -> right = deleteNode ( root -> right , temp -> key ) ; } return root ; } struct node * changeKey ( struct node * root , int oldVal , int newVal ) { root = deleteNode ( root , oldVal ) ; root = insert ( root , newVal ) ; return root ; } int main ( ) { struct node * root = NULL ; root = insert ( root , 50 ) ; root = insert ( root , 30 ) ; root = insert ( root , 20 ) ; root = insert ( root , 40 ) ; root = insert ( root , 70 ) ; root = insert ( root , 60 ) ; root = insert ( root , 80 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ given ▁ tree ▁ STRNEWLINE " ) ; inorder ( root ) ; root = changeKey ( root , 40 , 10 ) ; printf ( " Inorder traversal of the modified tree " inorder ( root ) ; return 0 ; }
Special two digit numbers in a Binary Search Tree | C program to count number of nodes in BST containing two digit special number ; A Tree node ; Function to create a new node ; If the tree is empty , return a new , single node ; Otherwise , recur down the tree ; Function to find if number is special or not ; Check if number is two digit or not ; Function to count number of special two digit number ; Driver program to test ; Function call , to check each node for special two digit number
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { struct Node * left ; int info ; struct Node * right ; } ; void insert ( struct Node * * rt , int key ) { if ( * rt == NULL ) { ( * rt ) = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; ( * rt ) -> left = NULL ; ( * rt ) -> right = NULL ; ( * rt ) -> info = key ; } else if ( key < ( ( * rt ) -> info ) ) insert ( & ( ( * rt ) -> left ) , key ) ; else insert ( & ( * rt ) -> right , key ) ; } int check ( int num ) { int sum = 0 , i = num , sum_of_digits , prod_of_digits ; if ( num < 10 num > 99 ) return 0 ; else { sum_of_digits = ( i % 10 ) + ( i / 10 ) ; prod_of_digits = ( i % 10 ) * ( i / 10 ) ; sum = sum_of_digits + prod_of_digits ; } if ( sum == num ) return 1 ; else return 0 ; } void countSpecialDigit ( struct Node * rt , int * c ) { int x ; if ( rt == NULL ) return ; else { x = check ( rt -> info ) ; if ( x == 1 ) * c = * c + 1 ; countSpecialDigit ( rt -> left , c ) ; countSpecialDigit ( rt -> right , c ) ; } } int main ( ) { struct Node * root = NULL ; int count = 0 ; insert ( & root , 50 ) ; insert ( & root , 29 ) ; insert ( & root , 59 ) ; insert ( & root , 19 ) ; insert ( & root , 53 ) ; insert ( & root , 556 ) ; insert ( & root , 56 ) ; insert ( & root , 94 ) ; insert ( & root , 13 ) ; countSpecialDigit ( root , & count ) ; printf ( " % d " , count ) ; return 0 ; }
Construct Special Binary Tree from given Inorder traversal | program to construct tree from inorder traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Prototypes of a utility function to get the maximum value in inorder [ start . . end ] ; Recursive function to construct binary of size len from Inorder traversal inorder [ ] . Initial values of start and end should be 0 and len - 1. ; Find index of the maximum element from Binary Tree ; Pick the maximum value and make it root ; If this is the only element in inorder [ start . . end ] , then return it ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of the maximum value in arr [ start ... end ] ; 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 program to test above functions ; Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 ; Let us test the built tree by printing Insorder traversal
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; int max ( int inorder [ ] , int strt , int end ) ; struct node * newNode ( int data ) ; struct node * buildTree ( int inorder [ ] , int start , int end ) { if ( start > end ) return NULL ; int i = max ( inorder , start , end ) ; struct node * root = newNode ( inorder [ i ] ) ; if ( start == end ) return root ; root -> left = buildTree ( inorder , start , i - 1 ) ; root -> right = buildTree ( inorder , i + 1 , end ) ; return root ; } int max ( int arr [ ] , int strt , int end ) { int i , max = arr [ strt ] , maxind = strt ; for ( i = strt + 1 ; i <= end ; i ++ ) { if ( arr [ i ] > max ) { max = arr [ i ] ; maxind = i ; } } return maxind ; } 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 ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; printInorder ( node -> right ) ; } int main ( ) { int inorder [ ] = { 5 , 10 , 40 , 30 , 28 } ; int len = sizeof ( inorder ) / sizeof ( inorder [ 0 ] ) ; struct node * root = buildTree ( inorder , 0 , len - 1 ) ; printf ( " Inorder traversal of the constructed tree is " printInorder ( root ) ; return 0 ; }