Posts

Showing posts from August, 2022

Flatten BST to sorted list

  // Flatten BST to Sortlisted #include <bits/stdc++.h> using namespace std ; struct Node {     int data ;     struct Node * left ;     struct Node * right ;     Node ( int val ){         data = val ;         left = NULL ;         right = NULL ;     } }; void fun ( Node * parent ){     Node * curr = parent ;     while ( curr != NULL )         cout << curr -> data << " " , curr = curr -> right ; } void inorder ( Node * curr , Node * & prev ){     if ( ! curr ) return ;     inorder ( curr -> left , prev );     prev -> left = NULL ;     prev -> right = curr ;     prev = curr ;     inorder ( curr -> right , prev ); } Node * flatten ( Node * root ){     Node * dummy = new Node ( - 1 );     Node * prev = dummy ;     inorder ( root , prev );     prev -> left = NULL ;     prev -> right = NULL ;     Node * ret = dummy -> right ;     return ret ; } int main (){         #ifndef ONLINE_JUDGE freopen ( &q

Merge Two Balanced Binary Search Trees

  #include <bits/stdc++.h> using namespace std ; #define shailesh ios :: sync_with_stdio (false); cin . tie ( 0 ); cout . tie ( 0 ); #define int long long int #define vi vector < int > #define pii pair < int, int > #define vii vector < pii > #define rep ( i , a , b ) for(int i = a; i < b; i ++ ) #define ff first #define ss second const int N = 1e5 + 10 ; bool isPowerOfTwo ( int x ){       return x && ( ! ( x & ( x - 1 ))); } bool isPrime ( int n ) {     if ( n <= 1 )     return false ;     if ( n <= 3 )     return true ;     if ( n % 2 == 0 || n % 3 == 0 )     return false ;     for ( int i = 5 ; i * i <= n ; i = i + 6 )     if ( n % i == 0 || n % ( i + 2 ) == 0 )     return false ;     return true ; } bool isPalindrome ( string S ) {     for ( int i = 0 ; i < S . length () / 2 ; i ++ ) {         if ( S [ i ] != S [ S . length () - i - 1 ] ) {        

Normal BST to Balanced BST

  #include <bits/stdc++.h> using namespace std ; #define shailesh ios :: sync_with_stdio (false); cin . tie ( 0 ); cout . tie ( 0 ); #define int long long int #define vi vector < int > #define pii pair < int, int > #define vii vector < pii > #define rep ( i , a , b ) for(int i = a; i < b; i ++ ) #define ff first #define ss second const int N = 1e5 + 10 ; bool isPowerOfTwo ( int x ){       return x && ( ! ( x & ( x - 1 ))); } bool isPrime ( int n ) {     if ( n <= 1 )     return false ;     if ( n <= 3 )     return true ;     if ( n % 2 == 0 || n % 3 == 0 )     return false ;     for ( int i = 5 ; i * i <= n ; i = i + 6 )     if ( n % i == 0 || n % ( i + 2 ) == 0 )     return false ;     return true ; } bool isPalindrome ( string S ) {     for ( int i = 0 ; i < S . length () / 2 ; i ++ ) {         if ( S [ i ] != S [ S . length () - i - 1 ] ) {