Posts

Find the Closest Element in BST

https: //practice.geeksforgeeks.org/problems/find-the-closest-element-in-bst/1/ Input: 10   / \   2 11   / \   1 5   / \   3 6   \   4 K = 13 Output: 2 Explanation: K=13. The node that has value nearest to K is 11. so the answer is 2 class Solution { public:     void helper ( Node * root , int & mn_dif , int & k )     {         if ( root = NULL )             return ;         mn_dif = min ( mn_dif , abs ( root -> data - k ));         if ( root -> data > k )             helper ( root -> left , mn_dif , k );         else if ( root -> data < k )             helper ( root -> right , mn_dif , k );         else             return ...

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Image
Example 1: Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#] Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. Example 2: Input: root = [] Output: [] class Solution { public:     Node * connect ( Node * root )     {         Node * p1 = root , * p2 ;         while ( p1 != NULL )         {             p2 = p1 ;             while ( p2 != NULL )             {                 if ( p2 -> left )                     p2 -> left -> next = p2 -> right ;       ...

Image Multiplication

https://practice.geeksforgeeks.org/problems/image-multiplication0627/1 Input: 1 / \ 3 2 / \ / \ 7 6 5 4 / \ \ / \ \ 11 10 15 9 8 12 Output: 332 Explanation: Sum = (1*1) + (3*2) + (7*4) + (6*5) + (11*12) + (15*9) = 332 class Solution {     public:     void treeHelper ( Node * a , Node * b , long long int & ans )     {         if (a== NULL ||b== NULL )         return ;         long long int temp=( a -> data * b -> data )%( 1000000007 );         ans=(ans+temp)%( 1000000007 );         treeHelper ( a -> left , b -> right , ans);         treeHelper ( a -> right , b -> left , ans);     }   ...

Build BST from preOrder In O(n)

Image
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right. Example 1: Input: preorder = [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12] class Solution { public:     int i;     TreeNode * build(vector< int > & preorder, int mn, int mx)     {         if (i >= preorder.size())             return NULL ;         if (preorder[...

Path Sum III OR Number of paths with target sum

Image
Given the   root   of a binary tree and an integer   targetSum , return   the number of paths where the sum of the values along the path equals   targetSum . The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). Example 1: Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 Output: 3 Explanation: The paths that sum to 8 are shown. class Solution { public:     void helper( TreeNode * root , int & ans ,                     map < long long int , long long int > & mp ,                                  long long int sum , int & target )     {         if ( root == NULL )             return ;   ...

Subarrays with sum K or target

Input: N = 5 Arr = {10 , 2, -2, -20, 10} k = -10 Output: 3 Explaination: Subarrays: arr[0...3], arr[1...4], arr[3..4] have sum exactly equal to -10. class Solution {     public:     int findSubArraySum( int Arr [], int N , int k )     {         map< int , int >mp;         int ans=0,sum=0;         mp[0]=1;                 for ( int i=0;i<N;i++)         {             sum+=Arr[i];             if (mp.find(sum-k)!=mp.end())             ans+=mp[sum-k];             mp[sum]++;         }         return ans;     } };

Maximum Leaf to Root path sum

Image
class Solution {     public:     void treeHelper( Node * root , int & ans , int sum )     {         if ( root == NULL )         return ;         sum += root ->data;         if ( root ->left== NULL && root ->right== NULL )         {             ans =max( ans , sum );             return ;         }         treeHelper( root ->left, ans , sum );         treeHelper( root ->right, ans , sum );     }     int maxPathSum( Node * root )     {         int ans= INT_MIN ;         treeHelper( root , ans,0);         return ans;     } };

Build BST from preOrder and find postOrder

  //Bhaskar Varshney #include <bits/stdc++.h> using namespace std; struct TreeNode {     int val;     TreeNode *left;     TreeNode *right;     TreeNode *nextRight;     TreeNode() : val(0), left( nullptr ),           right( nullptr ), nextRight( nullptr ) {}     TreeNode( int x ) : val( x ), left( nullptr ),           right( nullptr ), nextRight( nullptr ) {} }; void PostOrder( TreeNode * root ) {     if ( root == NULL )         return ;     PostOrder( root ->left);     PostOrder( root ->right);     cout << root ->val << " " ; } void bfs( TreeNode * root ) {     queue < TreeNode *> q;     q.push( root );     q.push( NULL );     while (!q.empty())     {         TreeNode *temp = q.front(...

Build BST from postOrder

  // Input: // n=6 // postOrder: 1 7 5 50 40 10 // Output: // Inorder: 1 5 7 10 40 50 //   Tree will be : //        10 //      /   \ //    5       40 //  /   \      \ // 1     7      50 //Bhaskar Varshney #include <bits/stdc++.h> using namespace std; struct TreeNode {     int val;     TreeNode *left;     TreeNode *right;     TreeNode *nextRight;     TreeNode() : val(0), left( nullptr ),           right( nullptr ), nextRight( nullptr ) {}     TreeNode( int x ) : val( x ), left( nullptr ),           right( nullptr ), nextRight( nullptr ) {} }; void PreOrder( TreeNode * root ) {     if ( root == NULL )         return ;     cout << root ->val << " " ;     PreOrder( ...

BST to greater sum tree

  // Input: //            2 //          /    \ //         1      6 //               /  \ //              3    7 // Output: 18 16 13 7 0 (InOrder) // Explanation: // Every node is replaced with the sum of nodes greater than itself. // The resultant tree is: //                16 //              /    \ //            18       7 //                   /   \ //                  13    0 //Bhaskar Varshney #include <iostream> #include <queue> using namespace std; struct TreeNode {     int val;     TreeNode *left;     TreeNode *rig...

BST from sorted Linked List

// Bhaskar Varshney #include <iostream> #include <vector> using namespace std; struct ListNode {     int val;     ListNode *next;     ListNode() : val(0), next( nullptr ) {}     ListNode( int x ) : val( x ), next( nullptr ) {}     ListNode( int x , ListNode * next ) : val( x ), next( next ) {} }; struct TreeNode {     int val;     TreeNode *left;     TreeNode *right;     TreeNode( int x ) : val( x ), left( nullptr ), right( nullptr ) {} }; ListNode * BuildList() {     ListNode *head = NULL , *temp;     int choice = 1;     while (choice == 1)     {         ListNode *newnode = ( ListNode *)malloc( sizeof ( ListNode ));         cout << "Enter data : " ;         cin >> newnode->val;         newnode->next = 0;       ...

Iterative Pre, Post And Inorder Traversals Of Binary Tree

void iterativePrePostInTraversal( Node * root ) {     // pair of node and number of visits to the i-th node.     //  if number of visits=0, then print in pre and move to left.     //  if number of visits=1, then print in In and move to right.     //  if number of visits=2, then print in post and pop the value at top;     stack < pair < Node *, int >> st;     vector < int > pre, post, in;     st.push({ root , 0});     pair < Node *, int > temp;     while (!st.empty())     {         temp = st.top();         if (temp.second == 0)         {             st.top().second++;             pre.push_back(temp.first->data);             if (temp.first->left)             ...

Boundary Traversal of binary tree

struct Node {     int data;     Node * left, * right; }; class Solution { public:     void call_left ( vector < int > & v , Node * root )     {         if ( root == NULL )             return ;         if ( root ->left == NULL && root ->right == NULL )             return ; // don't push the leaf nodes.         v . push_back ( root ->data);         if ( root ->left)             call_left ( v , root ->left);         else             call_left ( v , root ->right);     }     void call_leaves ( vector < int > & v , Node * root )     {         if ( root == NULL )             return ;   ...