Lecture 64: Binary Tree FAANG Interview Questions || Part-2

  Рет қаралды 399,333

CodeHelp - by Babbar

CodeHelp - by Babbar

Күн бұрын

Пікірлер: 493
@CodeHelp
@CodeHelp 2 жыл бұрын
Do Visit Relevel: relvl.co/y1u3
@namanshah2688
@namanshah2688 2 жыл бұрын
Another solution for vertical order traversal using map data structure class Solution { public: //Function to find the vertical order traversal of Binary Tree. vector verticalOrder(Node *root) { vector ans; if(root == NULL) return ans; queue q; q.push({root,0}); map mymap; while(!q.empty()) { auto it = q.front(); q.pop(); Node* front = it.first; int m = it.second; mymap[m].push_back(front->data); if(front->left) q.push({front->left,m-1}); if(front->right) q.push({front->right,m+1}); } for(auto x : mymap) { for(auto it : x.second) { ans.push_back(it); } } return ans; } };
@cat-codes1on1
@cat-codes1on1 2 жыл бұрын
bhaiya comment me sab thank you thank you bolte rehte hai...lekin jo aap question dete ho uska discusion koi nahi karta comment section me...immature audience...jo aapne padhaya hai us see related comments honge toh aur bhi badiya hoga...ek video me bol diya thank you ye toh saari videos ke comment section me...
@dipuldev248
@dipuldev248 2 жыл бұрын
BHAIYA QUESTION KAI BAAD USKA DRY KARWADIA KARO PLZZ SAMAJH NAHI AARAHA MAP OR QUEUE MAI KAISAI PUT KAR RAHA HAI VALUE
@harshitsharma5647
@harshitsharma5647 2 жыл бұрын
Bhaiya aaaj pakaa bol sakta hu ki Binary Tree aaaa gayi Again and Again Thankyou bhaiya 😌😌😌😌
@SatyamKumar-pd8qy
@SatyamKumar-pd8qy 2 жыл бұрын
Line 122 in vertical traversal of binary tree question. samajh nai aya. Please anyone help
@anshumansharma1069
@anshumansharma1069 Жыл бұрын
vector diagonal(Node *root) { vector diagonal; if(root==NULL) return diagonal; queue q; q.push(root); while(q.empty()!=true){ Node *temp = q.front(); q.pop(); while(temp!=NULL){ diagonal.push_back(temp->data); q.push(temp->left); temp = temp->right; } } return diagonal; } // Homework..... Immensely Appreciate the way he teaches us💖💖
@arijitdubey
@arijitdubey 5 ай бұрын
Thank you so much for this!
@souravsikaria4387
@souravsikaria4387 2 жыл бұрын
for vertical traversal of binary tree if we are using level order traversal then maintaining level is redundant, we can do it only by using horizontal distance. Attaching code reference for better underatanding. vector verticalOrder(Node *root) { map mp; queue q; vector ans; if(!root) return ans; q.push(make_pair(root,0)); while(!q.empty()) { pair p = q.front(); q.pop(); Node *curr = p.first; int hd = p.second; mp[hd].push_back(curr->data); if(curr->left) q.push(make_pair(curr->left,hd-1)); if(curr->right) q.push(make_pair(curr->right,hd+1)); } for(auto it: mp) { for(auto i : it.second) { ans.push_back(i); } } return ans; }
@AjayYadav-um1oj
@AjayYadav-um1oj 2 жыл бұрын
ya you are right i also thought that it can solve only by using map queue
@rahulprasad3575
@rahulprasad3575 2 жыл бұрын
nice brother you gave a new perspective : )
@jayasrivastava3221
@jayasrivastava3221 2 жыл бұрын
is your code acceptable on leetcode ? i am getting tle
@shubhammittal5342
@shubhammittal5342 2 жыл бұрын
@@jayasrivastava3221 its working fine
@allindiachannel2290
@allindiachannel2290 2 жыл бұрын
even i thought of that
@nishanttomer2555
@nishanttomer2555 Жыл бұрын
Following this series from lecture 1 but this lecture was hard to digest. Watched it multiple times but still not very clear. Btw, Thanks a lot brother for this amazing series
@govindsuryavanshi6653
@govindsuryavanshi6653 Жыл бұрын
First I have completed all DSA series and now conclude this is Greatest ever DSA series to exist on youtube or paid courses. Your contribution will be remembered. You're God of DSA for us🙇‍♂ Thanks you.
@yashmahamune8765
@yashmahamune8765 2 жыл бұрын
Bhaiya aap joh effort laga rahe ho hamare liye , itna raat raat bhar jaag kar sikhana,videos banana , aaj ke time me koi itna nahi karta bhaiya, truely u r selfless bhaiya, very proud to have a great teacher and mentor like u in this amazing journey , Lots of Love to u bhaiya, always keep growing😇😌💫❤🙏
@lalitsharma6132
@lalitsharma6132 2 жыл бұрын
Bhaiya aap to consistency ko dil pe le lie 😂😂
@38.pranjalmishra48
@38.pranjalmishra48 Жыл бұрын
Map is use for reduce the time complexity. When we have to compare thing and for that we use looping which have more complexity (O(NXM)) so we replace it using map by which their complexity educe to O(N) . Thankyou Bhaiya ❤🙏
@priyalvyas1501
@priyalvyas1501 Жыл бұрын
The time complexity for searching elements in std::map is O(log n) and for Level order Traversal it is O(n). Hence total TC is O(n*logn).
@AbhishekChoudharyB
@AbhishekChoudharyB 8 ай бұрын
For diagonal traversal, we push root in a queue first, Then while queue is not empty =>We take temp=q.front(), q.pop() Then while (temp!=NULL) => We store temp's data into ans vector =>push temp->left in queue =>Assign temp=temp->right At last return ans
@divyareddy7622
@divyareddy7622 2 жыл бұрын
Bhaiya please continue your dry runs after each question it helps sooo much!! 🥺🥺❤ thank you so muchh!!!
@delta_mohit
@delta_mohit Жыл бұрын
Khud se kar le bhai
@therealartist9
@therealartist9 9 ай бұрын
@@delta_mohitkhud se krna hota to yaha ni ate na mere bhai
@delta_mohit
@delta_mohit 9 ай бұрын
@@therealartist9 bhai khud se nahi karoge to kahi bhi chale jao kisi se bhi padh lo, nahi Sikh paoge dsa
@therealartist9
@therealartist9 9 ай бұрын
@@delta_mohithn bhai bilkul correct kaha aapney but as a beginner dry run ki need padti hai bhai matlab mai to bilkul hi beginner hu
@HarshKumar-mx9nj
@HarshKumar-mx9nj 8 ай бұрын
​@@therealartist9bhai tu 64th lecture pr hai ab dry run to khud se ho jana chahiye
@keshavgambhir9894
@keshavgambhir9894 2 жыл бұрын
Present bhaiya Consistency op 🔥🔥 Attending all lectures religiously Commenting for a better reach
@suvigyabasnotra7378
@suvigyabasnotra7378 2 жыл бұрын
47:00 Little documentation for what each map, queue and vector is doing and storing here would've helped to keep a track of these nested data structures.
@Shivam-kz2dg
@Shivam-kz2dg 2 жыл бұрын
Watch his stl in 1hr video
@divyagupta6854
@divyagupta6854 Жыл бұрын
I think he took some time to explain that part, go through that part starting from 39:00 once, or twice, or thrice if you don't understand.
@sanskarkumar028
@sanskarkumar028 Жыл бұрын
thanku sir You tube me itne acche level ke questions ,itne acche tarike se batane ke liye dhanyawaad . Keep guiding us bhaiya .... I am from Nit Bhopal.. cse
@RajKumar-vq1nm
@RajKumar-vq1nm 2 жыл бұрын
Consistency match kar pa raha hu or bada maza araha hai...Thanks from bottom of the heart.
@shivkumar-og4ow
@shivkumar-og4ow 2 жыл бұрын
present guru ji appka to next level ki consistency hai.. aag laga diye hai🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
@alexrcrew1975
@alexrcrew1975 2 жыл бұрын
calling traverseleaf() two times can be avoided , call it one time for root node and make sure to check if root is itself a leaf node then push it to vector and return it
@utkarshpatidar167
@utkarshpatidar167 2 жыл бұрын
but we already pushback root element And than if we try this Root data will be pushed again..! Understand it by taking a example of only 1 node
@ashayjain2514
@ashayjain2514 Жыл бұрын
@@utkarshpatidar167 after pushing root in the vector,we can add one more base condition that if root is a leaf node return the vector,then one function call for printing leaf nodes is sufficient. void a(Node* root,vector&v) { if(root==NULL || (root->left==NULL && root->right==NULL)) return; v.push_back(root->data); if(root->left) { a(root->left,v); } else if(root->right) { a(root->right,v); } } void b(Node* root,vector&v) { if(root==NULL || (root->left==NULL && root->right==NULL)) return; v.push_back(root->data); if(root->right) { b(root->right,v); } else if(root->left) { b(root->left,v); } } void s(Node* root,vector&v) { if(root==NULL) return; s(root->left,v); if(root->left==NULL && root->right==NULL) v.push_back(root->data); s(root->right,v); } vector boundary(Node *root) { //Your code here vectorv; if(root==NULL) return v; v.push_back(root->data); if(root->left==NULL && root->right==NULL) return v; a(root->left,v); s(root,v); vectord; b(root->right,d); reverse(d.begin(),d.end()); for(auto it:d) v.push_back(it); return v; }
@Pawan_Sharma99
@Pawan_Sharma99 Жыл бұрын
In the 2nd question (vertical order traversal), actually we don't need another map inside a map. As we are only concerned about the number line position of a node, it's quite useless to keep track of levels. Try solving with map its much easier and works too
@anmol3
@anmol3 9 ай бұрын
No, it seems to work but it won't work
@Pawan_Sharma99
@Pawan_Sharma99 9 ай бұрын
class Solution { public: //Function to find the vertical order traversal of Binary Tree. vector verticalOrder(Node *root) { //Your code here // level, numberline queue q; q.push({root,{0,0}}); // no.line level nodes map m; while(!q.empty()){ pair p=q.front(); q.pop(); Node* curr=p.first; int lvl=p.second.first; int nl=p.second.second; m[nl].push_back(curr->data); if(curr->left){ q.push({curr->left,{lvl+1,nl-1}}); } if(curr->right){ q.push({curr->right,{lvl+1,nl+1}}); } } vector ans; for(auto i: m){ for(auto j: i.second){ ans.push_back(j); } } return ans; } }; @@anmol3
@aditiagarwal3646
@aditiagarwal3646 8 ай бұрын
No it's not needed to store levels because level order traversal in itself allows the nodes to stored level wise .Hence it's a extra feature to keep level which is of no use @@anmol3
@raviranjan3458
@raviranjan3458 4 ай бұрын
At last when for loop is starting how it can take the first number 4 and all. In dry run how he will understand that it takes number from less horizontal distance to high horizontal distance
@AnmolGupta-oj4lm
@AnmolGupta-oj4lm 3 ай бұрын
Thanks bhaiya 1 baar m Vertical Order Traversal samajh aa gya .. apke samjhate hi code to khud hi likh liya ... intuitiion hi itna badhiya develop krdiye the ...
@Adarsh-mn7pl
@Adarsh-mn7pl 2 жыл бұрын
Homework Question: ArrayList diagonal = new ArrayList(); if(root == null)return diagonal; Queue q = new LinkedList(); q.add(root); while(q.size()>0){ Node temp = q.remove(); while(temp != null){ if(temp.left != null)q.add(temp.left); diagonal.add(temp.data); temp = temp.right; } } return diagonal;
@AbhishekChoudharyB
@AbhishekChoudharyB 8 ай бұрын
Which language is this
@anubhavdeepankar6681
@anubhavdeepankar6681 4 ай бұрын
Such a calm and composed answer for vertical order traversal at 34:00 , best solution explanation
@dimpleaggarwal9302
@dimpleaggarwal9302 Жыл бұрын
I think in vertical order traversal 40:27 there was no need for taking level in map as it only increases the complexity of data structure instead we can do this question with just horizontal distance public: //Function to find the vertical order traversal of Binary Tree. vector verticalOrder(Node *root) { vector ans; map node; queue q; if(root==NULL){ return ans; } q.push(make_pair(root,0)); while(!q.empty()){ pair temp=q.front(); q.pop(); Node * tempNode= temp.first; int hd= temp.second; node[hd].push_back(tempNode->data); if(tempNode->left){ q.push(make_pair(tempNode->left,hd-1)); } if(tempNode->right){ q.push(make_pair(tempNode->right,hd+1)); } } for(auto i: node){ for(auto j: i.second){ ans.push_back(j); } } return ans; }
@049bite_gauravkumarsoni3
@049bite_gauravkumarsoni3 Жыл бұрын
thank you bro,,, i was to confused with love bhaiya's solution . then i saw your comment and i tried to do it without level data, then it is to simple to arrange data and solve easily
@viveknandan4950
@viveknandan4950 Жыл бұрын
cool
@nana_patekar_
@nana_patekar_ Жыл бұрын
your answer is actually easy to understand thank you
@omkumarjha2745
@omkumarjha2745 Жыл бұрын
Thanks bro now the code is easy to understand.
@priyalvyas1501
@priyalvyas1501 Жыл бұрын
The time complexity for searching elements in std::map is O(log n) and for Level order Traversal it is O(n). Hence total TC is O(n*logn).
@harshitagarg2544
@harshitagarg2544 4 ай бұрын
I must say that because of you bhaiya I am able to learn and keep up with learning...aap bata detey ho yeh thoda hard hai shaanti se krogey ek do baar aaram se samjh aajayega aur aata bhi hai ...Thank You Love Bhaiya...We all Love You.
@anjaan937
@anjaan937 2 жыл бұрын
maja aagya bhaiya , video 2 baar dekhi top view k liye lekin samj me aagya achhe se , dhnywaad aapka guruji
@HARSHSINGH-vs4ot
@HARSHSINGH-vs4ot Жыл бұрын
Coding is not difficult ' is being consistent!!
@madhabkafle8072
@madhabkafle8072 2 жыл бұрын
Answer to "College start hogaye qa ?" Roz hote he someday 8a.m -02pm Some day 10a.m - 5pm 😔😔
@KPCoder
@KPCoder 2 жыл бұрын
Thanks you sir, excellent content, no one can explain like you from basic 🙏 god bless you
@anandmaurya6384
@anandmaurya6384 2 ай бұрын
class Solution { vector fun(Node * root){ // map for storing element in vertical order: mapm; // elements corespond to a vertical path // for level wise traversal : queueq; // it will store node with there vertical path: q.push(make_pair(root , 0)); //root while(!q.empty()){ pair p = q.front(); // storing first element q.pop(); // removing first element. // Now we have to map the node* value with the corresponding //vertical path to store it; Node * temp = p.first; int vp = p.second; // puting inside the map as per the vertical path m[vp].push_back(temp->data); // we have successfully stored the element according // to there level and vertical path // pushing the next elements as per there verical path if(temp->left) // storing the left part so verical path will decrease q.push(make_pair(temp->left,vp-1)); if(temp->right) q.push(make_pair(temp->right,vp+1)); } // after that much operations all the elements will stored // in there coresponding vertical path vectorans; // for storing elements // since elements are stored in sortd order in map // hence all the element will stored in L-R vertical path // storing element for(auto i: m){ for(auto j: i.second){ ans.push_back(j); } } return ans; } public: //Function to find the vertical order traversal of Binary Tree. vector verticalOrder(Node *root) { //Your code here return fun(root); } }; Thank u sir
@adarshshrivastava410
@adarshshrivastava410 2 жыл бұрын
i did the zigzag question with stack!... i know i am over reacting but this is a big deal for me after struggling so much ... thanks to you bhaiya i think i have started to understand these ds.
@shiroyasha69
@shiroyasha69 2 жыл бұрын
mereko to abhi bhi smjh nhi aarha h kuch , jab koi smjhata hai tab hi solution nikal pata hu apne se ghnta soln niklta hi nhi lgta h mere liye nhi h programming 🥲
@adarshshrivastava410
@adarshshrivastava410 2 жыл бұрын
@@shiroyasha69 don't give up bro, thoda time to harr cheez ko lagta hai... Lage raho and once you get going there will be nothing that can stop you.
@shiroyasha69
@shiroyasha69 2 жыл бұрын
@@adarshshrivastava410 Yes bro sahi bola jitna time lagna hai lage DSA ko to pkka master krunga
@AmanSingh-br1nr
@AmanSingh-br1nr Жыл бұрын
@@shiroyasha69 mere sath bhii aisa hi h starting phase mein yahi dikkt aati haii
@VivianRodrigues-gn7vf
@VivianRodrigues-gn7vf Ай бұрын
In question number 3 there is no need of level at all , you can do it without level use the format that queue is going on (bfs traversal) . Due to the level the code is simply clumsy and difficult to dry run. vector verticalOrder(Node *root) { vectorans; if(root==NULL){ return ans; } map map1; //pair queue q; q.push(make_pair(root, 0)); while(!q.empty()){ int hl=q.front().second; Node * node=q.front().first; map1[hl].push_back(node->data); if(node->left){ q.push(make_pair(node->left,hl-1)); } if(node->right){ q.push(make_pair(node->right,hl+1)); } q.pop(); } for (auto& hd_map : map1) { for (int node_value : hd_map.second) { ans.push_back(node_value); } } return ans; }
@Mehndi_collections
@Mehndi_collections 10 ай бұрын
u can change these line by following code for simplicity 106 map nodes; 122. nodes[hd].push_back(frontNode->data); 131 to 139 for(auto i: nodes) for(auto j:i.second) ans.push_back(j);
@aniketk2500
@aniketk2500 10 ай бұрын
yep it will work on gfg ig but when you are solving on leetcode you also have to maintain the level of the node hence bhaiya's code is correct for both the platforms.
@darshanpatel9131
@darshanpatel9131 Жыл бұрын
00:00 Solve questions on traverse of trees and different types of views on trees 08:18 Implementing Zig Zag Traversal 17:12 Print left, leaf, and right parts of a tree 25:41 Vertical order traversal of binary tree 35:19 Create a mapping of level order nodes of horizontal nodes 44:43 Learned about vertical traversal and top view of binary tree 54:28 Learned about top, bottom, and left view of a binary tree 1:02:34 Printing the first node of each level in a binary tree from left to right using recursive traversal
@priyanshugoyal2539
@priyanshugoyal2539 2 жыл бұрын
Present Bhaiya Ji Ek number consistency!❤️🔥
@harshpandey4190
@harshpandey4190 Жыл бұрын
Literally I am lucky that I am following this course
@ThePrajaktaVlogs
@ThePrajaktaVlogs 2 жыл бұрын
apki mehnat dekh ke na bhaiyya badiya sa motivation ata h ekdm 😊
@syedFAHIM-el1wr
@syedFAHIM-el1wr 2 жыл бұрын
it is really good to see your videos without adds!
@amanaditya5602
@amanaditya5602 Жыл бұрын
A big THANK YOU for starting this series really helped me a lot to strengthen my DSA skills...
@kamalshrestha3416
@kamalshrestha3416 12 күн бұрын
def diagonal(root, ans): if root == None: return q = [] q.append(root) while(q): front = q[0] q.pop(0) # GO TO RIGHT AS MUCH AS POSSIBLE # PUT THE LEFT NODE IN QUEUE while(front!=None): ans.append(front.data) q.append(front.left) front = front.right return ans
@banghaters1965
@banghaters1965 Жыл бұрын
I felt low after zgzag traversal . I was unable to understand it. Yet I buckld down to understand it for 2 days lmao. and i did all the remaining codes on my self> hurrayyyyyyyyyyyyyyyyy
@suvigyabasnotra7378
@suvigyabasnotra7378 2 жыл бұрын
47:00 The structure of this code was really really tricky to understand because there are multiple things which are inside other things, which are inside other things, and those are inside something as well. So it got extremely tricky to keep a track of things.
@cat-codes1on1
@cat-codes1on1 2 жыл бұрын
haa bro sachme kaafi confusing ho gya hai btw you;re doing trees for the first time or you r revising
@suvigyabasnotra7378
@suvigyabasnotra7378 2 жыл бұрын
@@cat-codes1on1 First time. And I think he should explained the next questions before the current one because of obvious reasons. Though I did finally get the gist of the structuring of the maps and queues shown there by spending nearly 1.5 hours imagining how it's working. And next few questions were of help too.
@cat-codes1on1
@cat-codes1on1 2 жыл бұрын
@@suvigyabasnotra7378 HAA BRO MUJHE BHI 6HR LAG GYE AAJ PURA DIN TREE KA HI VIDEO DEKHA 2 BAAR 3 BAAR WESE KONSE SEMESTER ME HO TUM? ME TOH ABHI FIRST SEM ME HU? LEETCODE PAR KITNE QUESTION HO GYE TUMHARE??
@suvigyabasnotra7378
@suvigyabasnotra7378 2 жыл бұрын
@@cat-codes1on1 Let's just say I'm a lot older than you. And how did you start programming so early...? Did you start in 11th itself ? coz I started it way too late in my college and barely had any idea what to do in my first year.
@cat-codes1on1
@cat-codes1on1 2 жыл бұрын
bro i learned html ,css in class 8th but only basic then in 11th I chose Physical education but after giving my jee in feb 2021 I have lot of time till dec 2021 I learned C++ language and solved basic array string questions and bit javascript...but I want to level up by watching his lectures...
@ashishgoyal6256
@ashishgoyal6256 Жыл бұрын
@everyone sabhi ko ye baat keh raha hu jo jo ye playlist follow kr raha hai blindly kro ye playlist bhaiya ne jo que tree ke paid course me karae hai A to Z (literally) vahi is tree ki series me hai to hats off to you guru ji aapka content 😘🙏🙏🙏
@someshsangwan5302
@someshsangwan5302 2 жыл бұрын
Present sir !! wo kal m absent rh gya or aapko application likhna bhi bhul gya pr m kal wala homework kr lia sir . thnq sir
@komaldewnani5747
@komaldewnani5747 2 жыл бұрын
For question 3, there is no need to explicitly handle level in the map, as we're doing level order traversal so all the elements in the vector corresponding to a particular horizontal distance will follow a level order.
@udaypratapsingh8923
@udaypratapsingh8923 2 жыл бұрын
kaafi lambi soch hai aappki 😁😁😁
@justarandomguy6106
@justarandomguy6106 2 жыл бұрын
@@udaypratapsingh8923 apne to comment padh ke usko code bhi kr diya🙂
@udaypratapsingh8923
@udaypratapsingh8923 2 жыл бұрын
@@justarandomguy6106 dhanyavaad bhaiyaa batane ke liye
@harisrashid0773
@harisrashid0773 2 жыл бұрын
Actually this approach can be used to solve many modifications of this particular question.
@nishanklalitjain8435
@nishanklalitjain8435 2 жыл бұрын
@@harisrashid0773 can you explain left view ka condition
@parthshukla4377
@parthshukla4377 2 жыл бұрын
Ans for homework question of diagonal traversal of binary tree is vector diagonal(Node *root) { vector s; if(root == NULL) { return s; } queuep; p.push(root); while(!p.empty()){ Node* TopNode = p.front(); p.pop(); while(TopNode != NULL) { s.push_back(TopNode->data); if(TopNode->left != NULL) { p.push(TopNode->left); } TopNode = TopNode->right; } } return s; }
@Cluster-hr5my
@Cluster-hr5my 8 ай бұрын
Cant we do the last two view with mapping taking vertical level in place of hd and always vl+1 for both the null check
@heavenlypenguin6613
@heavenlypenguin6613 Жыл бұрын
Best explanations i have ever come across on youtube. Thanks for all of these videos!
@neerajmahapatra5239
@neerajmahapatra5239 2 жыл бұрын
line in description is very very inspiring..
@shashankmssp
@shashankmssp Жыл бұрын
//diagonal print using level order traversal approach vectorans; if(root==NULL) return ans; mapnodes; queueq; q.push(make_pair(root,make_pair(0,0))); while(!q.empty()){ pair temp=q.front(); q.pop(); Node* frontnode=temp.first; int hd=temp.second.first; int lvl=temp.second.second; while(frontnode){ if(frontnode->left) q.push(make_pair(frontnode->left,make_pair(hd+1,lvl+1))); nodes[hd][lvl].push_back(frontnode->data); frontnode=frontnode->right; } } for(auto i:nodes){ for(auto j:i.second){ for(auto k:j.second){ ans.push_back(k); } } } return ans;
@kushalgupta2041
@kushalgupta2041 8 ай бұрын
If we use two stacks in the ZigZag traversal i think it would be more easy to solve
@tarunganjoo8366
@tarunganjoo8366 Жыл бұрын
Q:vertical Order Traversal For Leetcode: vector verticalOrder(TreeNode *root) { map mapp; queue q; vector ans; if (root == NULL) return ans; q.push(make_pair(root, make_pair(0, 0))); while (!q.empty()) { pair temp = q.front(); q.pop(); TreeNode *front_Node = temp.first; int hr = temp.second.first; int level = temp.second.second; mapp[hr][level].push_back(front_Node->val); // first mapping of 0 horizontal row and 0 level is done for root node // now simple level order traversal if (front_Node->left) { q.push(make_pair(front_Node->left, make_pair(hr - 1, level + 1))); } if (front_Node->right) { q.push(make_pair(front_Node->right, make_pair(hr + 1, level + 1))); } } for (auto i : mapp) { vector output; for (auto j : i.second) { sort(j.second.begin(), j.second.end()); for (auto k : j.second) { output.push_back(k); } } ans.push_back(output); } return ans; } vector verticalTraversal(TreeNode *root) { return verticalOrder(root); }
@sahilchhabra2391
@sahilchhabra2391 2 жыл бұрын
bhaiya trees k questions se dar lagta tha, lagta THAA... thanks to you :D
@_Deepak__Verma
@_Deepak__Verma 10 ай бұрын
//diagonal traversing of binary tree // start-> void diagonalView(node* root, map &mp, int diagonal){ if(root==NULL) return; mp[diagonal].push_back(root->data); diagonalView(root->left, mp, diagonal+1); diagonalView(root->right, mp, diagonal); } void PrintDiagonal(node* root){ map mp; diagonalView(root, mp, 1); for(auto i: mp){ for(auto j: i.second){ cout
@utkarshasharma8679
@utkarshasharma8679 6 ай бұрын
Among One of the Best videos on tree ..................Keep it up......
@Thegr8mate
@Thegr8mate Жыл бұрын
nodes is acting as memory storage of respective nodes with their hd (ie x value) and lo( as y value) it just similar to cartesian plane, ab lene ko toh tesri value ek int bhi le sakte the par sir ne vector liya kyuki ek hi point pe multiple values exist karsakti like in example jo 5 and 6 k sath tha. aur ek clearity k liye bat jase map ek pair store karta h usi tarah map mein map triplet store karta h . aur fir kya sare (hd,lo) points k liye sir ne vecttor mein vaalue bharvali. ek bat sir ne hd phale rakha map mein kyu? kyuki map na apne aap hi starting vali value k hisab se pair ya triplet ko apne ape hi sort karleta h. ab ans mein store karne k liye teen for loop lagaye h notice karo toh phale do for loop mein correspondingly chalenge tesra for loop vector mein h .
@sukhjitsingh959
@sukhjitsingh959 Жыл бұрын
dry is better after every solution makes the doubt clear
@SaurabhKumar-vo9ul
@SaurabhKumar-vo9ul Жыл бұрын
We don't actually need to use level in 3rd question, we can just deal with the horizontal distance and get our result. Here is the code with some modification : vector verticalOrderTraversal(TreeNode *root) { vector result; if(root==NULL){ return result; } map m; queue q; q.push(make_pair(root,0)); while(!q.empty()){ TreeNode* Node = q.front().first; int hd = q.front().second; q.pop(); m[hd].push_back(Node->data); if(Node->left){ q.push( make_pair(Node->left,hd-1) ); } if(Node->right){ q.push( make_pair(Node->right,hd+1) ); } } for(auto i : m){ for(auto j : i.second){ result.push_back(j); } } return result; }
@KingBS89
@KingBS89 Ай бұрын
the code for vertical order traversal is not working with updated test cases because of TLE so here is the updated version of it it does not have much changes so still the lecture will help u to understand this code vector verticalOrder(Node *root) { vector ans; if (root == NULL) return ans; // hd lvl node's data map nodes; // node hd lvl queue q; // Initialize the queue with root node at hd = 0, lvl = 0 q.push(make_pair(root, make_pair(0, 0))); while (!q.empty()) { auto temp = q.front(); q.pop(); Node* frontNode = temp.first; int hd = temp.second.first; int lvl = temp.second.second; // Insert the current node's value into the map nodes[{hd, lvl}].push_back(frontNode->data); // Push the left and right children to the queue if (frontNode->left) q.push(make_pair(frontNode->left, make_pair(hd - 1, lvl + 1))); if (frontNode->right) q.push(make_pair(frontNode->right, make_pair(hd + 1, lvl + 1))); } for(auto i:nodes) { for(auto j:i.second) { ans.push_back(j); } } return ans; }
@mansisingh6493
@mansisingh6493 Жыл бұрын
how can the space complexity be O(n) in zigzag as aprt from the queue , a vector has also been difined everytime we go through the while loop
@prachigupta4605
@prachigupta4605 5 ай бұрын
Nice lecture mostly best than paid course of Fraz,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
@shikharverma5824
@shikharverma5824 2 жыл бұрын
im left behind and though in a way I want u to stop,but your consistency is on next level🔥🔥
@prabhatmishra6753
@prabhatmishra6753 2 жыл бұрын
vector diagonal(Node *root) { mapmp; queuepq; pq.push(make_pair(root,make_pair(0,0))); vectorans; int val1=0,val2=0; while(!pq.empty()) { pairp=pq.front(); Node* temp=p.first; pairq=p.second; int dis=q.first; int lvl=q.second; pq.pop(); mp[dis][lvl].push_back(temp->data); val2=max(val2,lvl); val1=min(val1,dis); if(temp->left) pq.push(make_pair(root->left,make_pair(dis-1,lvl+1))); if(temp->right) pq.push(make_pair(root->right,make_pair(dis+1,lvl+1))); } for(int i=0;i>=val1;i--) { for(int j=abs(i);j
@paarthjindal4100
@paarthjindal4100 5 ай бұрын
I have a doubt at 46:00 can we insert a vector into a vector in cpp using push_back ?
@praneetdebnath7171
@praneetdebnath7171 6 ай бұрын
In boundary of tree traversal why is it important to traverse the leaf node with leafTraversal(root->left,ans); and then leafTraversal(root->right,ans); Why can't we directly just call leafTraversal(root,ans)?
@ashutosh7133
@ashutosh7133 Жыл бұрын
vertical order traversal was explained really well, I tried other sources but the way he explained with all the whys was appreciable.
@hashmi__waseem
@hashmi__waseem 2 жыл бұрын
Present consistency 🔥🔥
@harshilbhatt9467
@harshilbhatt9467 Жыл бұрын
implementation of question 1 using stack: vector zigZagTraversal(Node* root) { vectorans ; int i=0 ; stackst ; stacks ; st.push(root) ; while(!s.empty() || !st.empty()) { while(!st.empty()) { Node*temp=st.top() ; st.pop() ; ans.push_back(temp->data) ; if(temp->left) s.push(temp->left) ; if(temp->right) s.push(temp->right) ; } while(!s.empty()) { Node*temp=s.top() ; s.pop() ; ans.push_back(temp->data) ; if(temp->right) st.push(temp->right) ; if(temp->left) st.push(temp->left) ; } } return ans ; }
@anuragpandey8165
@anuragpandey8165 2 жыл бұрын
31:51 Writing Line 165 and 167 separately when they could be combined can only be understood by the students who solve this question on their own and get that logical mistake......
@codingarena4297
@codingarena4297 2 жыл бұрын
Exactly bro. We could have directly passed root there . So no need to call the function two times, but suppose if there's only one element in the whole tree then it won't work.
@vijaybhaskar1413
@vijaybhaskar1413 Жыл бұрын
There is no need to store level because nowhere it's used only horizontal distance is needed.It's added complexity to the code
@JungleKiKahaniyan8
@JungleKiKahaniyan8 2 жыл бұрын
Present hu bhaiyaa!! Maja aa raha hai And college Start ho gaye to shaam ko dekh rahe hai
@prajjawalkumarpatel9360
@prajjawalkumarpatel9360 Жыл бұрын
Zig- Zag ki space and time complextity calculate karne ke upar video baneye-----
@shantanu8880
@shantanu8880 Жыл бұрын
In zig zac trivarsal w can also use a deque and keep a cnt of level
@dwivedi6037
@dwivedi6037 2 жыл бұрын
Aap Meri pahle mohabat ho jise subha utha ke dekha ka man karta hai bhaiya love you ♥️♥️♥️♥️
@dwivedi6037
@dwivedi6037 2 жыл бұрын
Bhiya aapne sab ko dil Diya hai mujhe like ap Mujhe Pyar Kam karte hai😭😭😭😭
@FanKClub
@FanKClub Жыл бұрын
congrates bhaiya for 300k subscriber at date 31 january 2023
@sunnysingh1267
@sunnysingh1267 2 жыл бұрын
Bhaiya for 3rd question this is also one approach, without using level, a little bit easier than your approach(just a little bit) public: //Function to find the vertical order traversal of Binary Tree. vector verticalOrder(Node *root) { //Your code here queueq; vector ans; map mp; if(root==NULL) return ans; q.push(make_pair(root,0)); while(!q.empty()) { pair temp=q.front(); q.pop(); Node*frontNode=temp.first; int hd=temp.second; mp[hd].push_back(frontNode->data); if(frontNode->left) q.push(make_pair(frontNode->left,hd-1)); if(frontNode->right) q.push(make_pair(frontNode->right,hd+1)); } for(auto i:mp) { for(auto j:i.second) { ans.push_back(j); } } return ans; } };
@updatedworld912
@updatedworld912 9 ай бұрын
best solution for diagonal void solve(Node*root,map &dia,int lvl){ if(root==NULL){ return; } dia[lvl].push_back(root->data); solve(root->left, dia, lvl + 1); solve(root->right, dia, lvl); } vector diagonal(Node *root) { map dia; vector ans; solve(root,dia,0); for(auto i:dia){ ans.insert(ans.end(), i.second.begin(), i.second.end()); } return ans; }
@prashantbirajdar9271
@prashantbirajdar9271 2 жыл бұрын
nice bhaiyaa mza aya lekin vertical traversal and zigzag tree traversal if those questions were solved in recursive approach that might be more understandable as compared to normal iterative approach...but over all session was so simple and easy to understand....thanks bhaiyaa...love u..keep it up !! for uss...
@shiroyasha69
@shiroyasha69 2 жыл бұрын
Ab lgrha hai, computer science mere liye nhi tha 🥲, leke glti krdi ab koi option bhi bacha , padhne k alawa
@wraith3108
@wraith3108 Жыл бұрын
how to solve question 3: vertical level in Leetcode facing issue in converting it to 2d vector?
@sarthak1391
@sarthak1391 Жыл бұрын
Awesome ! All concepts got cleared. Also solved homework question . Thanks!
@UzairKhan-qd3xu
@UzairKhan-qd3xu Жыл бұрын
bhaiya wouldnt it be better to use a doubly ended queue in Ques 1and then alternate pushing in front or back depending on the flag value: i have tried and it works below is the appropriate code: vector zigZagTraversal(Node* root) { vector result; if (root == nullptr) { return result; } deque dq; dq.push_back(root); bool leftToRight = true; while (!dq.empty()) { int levelSize = dq.size(); vector levelNodes(levelSize); for (int i = 0; i < levelSize; ++i) { if (leftToRight) { Node* node = dq.front(); dq.pop_front(); levelNodes[i] = node->data; if (node->left) dq.push_back(node->left); if (node->right) dq.push_back(node->right); } else { Node* node = dq.back(); dq.pop_back(); levelNodes[i] = node->data; if (node->right) dq.push_front(node->right); if (node->left) dq.push_front(node->left); } } result.insert(result.end(), levelNodes.begin(), levelNodes.end()); leftToRight = !leftToRight; } return result; } GFG reference for the last method used i searched for it. Insert the Range of Elements at Given Index Syntax of Vector insert() vector_name.insert(position, iterator1, iterator2)
@r060zeeshankhan9
@r060zeeshankhan9 2 жыл бұрын
// Love bhaiyya below is my solution , much simpler than your's solution and 100% acceptable at all platforms , the difference is that i didn't use the concept of level anywhere , just kept is simple , please consider it class Solution{ public: vector verticalOrder(Node *root) { vectorans; if(root==NULL){ return ans; } map mapping; queue q; q.push(make_pair(0,root)); int mini = INT_MAX; int maxi = INT_MIN; while(!q.empty()){ pair todo = q.front(); q.pop(); Node* node = todo.second; int distance = todo.first; int value = todo.second->data; mapping[distance].push_back(value); if(node->left){ q.push(make_pair(distance-1,node->left)); } if(node->right){ q.push(make_pair(distance+1,node->right)); } if(distance < mini){ mini = distance; } if(distance > maxi){ maxi = distance; } } int n = abs(mini) + maxi; for(int i=mini;i
@ex-pwian1190
@ex-pwian1190 Жыл бұрын
In top view, can we just print left part , right part and root?
@masumali8356
@masumali8356 Жыл бұрын
homework........for diagonal vector diagonal(Node *root) { vector diagonal; if(root==NULL) return diagonal; queue q; q.push(root); while(q.empty()!=true){ Node *temp = q.front(); q.pop(); while(temp!=NULL){ diagonal.push_back(temp->data); q.push(temp->left); temp = temp->right; } } return diagonal; }
@KripanshuSingh-b5s
@KripanshuSingh-b5s Ай бұрын
I have solved 1st question by using **DeQueue**.
@adityaraj-zm7zk
@adityaraj-zm7zk 2 жыл бұрын
Find the time and space complexity of the following code segment int GCD (int x, int y) { if y == 0 then return x else if x>= y AND y > 0 return GCD (y, x % y) else return 0; } iska step by step solve karke bhej do
@mind_blazed
@mind_blazed 6 ай бұрын
For top view -> print left nodes traversal and right nodes traversal Fir bottom view -> print leaf nodes Ye concept use nhi kr skte kya ?
@ashlok_chaudhary
@ashlok_chaudhary Жыл бұрын
Homework Solution;-) void diagonalelement(Node* root,int level,map &value){ if(root==NULL) return; value[level].push_back(root->data); diagonalelement(root->left,level+1,value); diagonalelement(root->right,level,value); } vector diagonal(Node *root) { vector ans; if(root==NULL) return ans; map value; diagonalelement(root,0,value); for(auto i: value) for(auto j: i.second) ans.push_back(j); return ans; }🙃
@shivamdevrani1330
@shivamdevrani1330 Жыл бұрын
i use this approach using level order traversal but it is not passing the test cases// vector diagonal(Node *root) { vector ans; if(root==NULL) return ans; queue q; q.push(make_pair(root,0)); map mp; while(!q.empty()) { pair temp=q.front(); q.pop(); int lvl=temp.second; root=temp.first; mp[lvl].push_back(root->data); if(root->left!=NULL) q.push(make_pair(root->left,lvl+1)); if(root->right!=NULL) q.push(make_pair(root->right,lvl)); } for(auto i:mp) { for(auto j:i.second) { ans.push_back(j); } } return ans; }
@nishugupta1001
@nishugupta1001 7 күн бұрын
@@shivamdevrani1330 some test cases are passed but not all vector diagonalPath(BinaryTreeNode* root) { // Write your code here. vectorans; if(root == NULL) { return ans; } mapm; queueq; q.push(make_pair(root,make_pair(0,0))); while(!q.empty()) { pair temp= q.front(); q.pop(); BinaryTreeNode* frontNode = temp.first; int hd = temp.second.first; int lvl = temp.second.second; m[hd][lvl].push_back(frontNode->data); // coutright,make_pair(hd,lvl+1))); } } for(auto i : m) { // sort(); for(auto j : i.second) { for(auto k : j.second) { ans.push_back(k); } } } return ans; } please improve it
@paarthjindal4100
@paarthjindal4100 5 ай бұрын
At 46:00 I have a doubt can we insert a vector into a vector in cpp using push_back ?
@alishachhabra5910
@alishachhabra5910 Жыл бұрын
Bhaiyaa !!..I am very stressed as I am not able to exactly grasp the content you are delivering.. Finding it a bit difficult to understand 🥺🥺🥺🥺🥺
@zimstuds7430
@zimstuds7430 2 жыл бұрын
1:10:28 kya mast padhaya🔥🔥 🔥🔥 tha apne, hint ki zarurat nhi padi
@hi_nehra1095
@hi_nehra1095 Жыл бұрын
vertical order traversal ka logic pura smjh aa gya but implementation bhot complex h, or java m convert kse kru smjh hi aa rha
@aisharawat9102
@aisharawat9102 3 ай бұрын
What if we dont call traverseLeaf function separately for left and right subtree ...but simply for the root for once...why it wont work.
@acousticanshu9364
@acousticanshu9364 10 ай бұрын
Thank you sir ❤❤, but you made vertical order traversal problem very complex , it can be solved without tracking the level because we are doing level order traversal though queue , it can be easy - class Solution { public: //Function to find the vertical order traversal of Binary Tree. vector verticalOrder(Node *root) { mapm; queueq; q.push(make_pair(root,0)); while(!q.empty()) { pairtemp=q.front(); q.pop(); int hd=temp.second; m[hd].push_back(temp.first->data); if(temp.first->left) q.push(make_pair(temp.first->left, hd-1)); if(temp.first->right) q.push(make_pair(temp.first->right, hd+1)); } vectorresult; for (auto i :m) { for(auto j:i.second) { result.push_back(j); } } return result; } };
@priyanshisharma5115
@priyanshisharma5115 7 ай бұрын
samjha gye bhai aap bhadiya tareeke se
@dep2460
@dep2460 2 жыл бұрын
College toh ho rakhe h start Bhaiya,, raat ko hi time milta h,, btw on linked list video will cover soon
@dep2460
@dep2460 2 жыл бұрын
After one month covered till this
@adityaawasthi7694
@adityaawasthi7694 2 жыл бұрын
ab kidhar tak cover hogya? and konse year se ho?
@ayushrawat7951
@ayushrawat7951 2 жыл бұрын
@@adityaawasthi7694 tum konse sem ke ho bhai?
@Danish-saifi1
@Danish-saifi1 Жыл бұрын
​@@ayushrawat7951 Kitna hua
@anjali61371
@anjali61371 Жыл бұрын
Can you please help me how to handle college studies and this course? I always fail to handle both the things together
@avishkarpatil5871
@avishkarpatil5871 10 ай бұрын
1:10:19 H / W - Diagonal Traversal of Binary Tree // Simple Code using MultiMap void getDiagonal(Node *root, multimap &m, int indx){ if(root == NULL) return; m.insert({indx, root->data}); getDiagonal(root->left, m, indx-1); getDiagonal(root->right, m, indx); } vector diagonal(Node *root) { multimap m; queue q; getDiagonal(root, m, 0); vector ans; for(auto i : m){ ans.push_back(i.second); } return ans; }
@prajjawalkumarpatel9360
@prajjawalkumarpatel9360 Жыл бұрын
map use karne get and put method O(1) mai performe ho hata hai jis se time complextiy O(N) hogi
@akashreddy7860
@akashreddy7860 Жыл бұрын
Great explanation for boundary traversal
@programmer938
@programmer938 2 жыл бұрын
Please try to explain why we are doing each step like previous videos....this video was too hard to understand
@chetansaini7644
@chetansaini7644 2 жыл бұрын
their is no need to map element according to their level(vertical traversal).because we are already traversing by level.
@anshikasinghal5863
@anshikasinghal5863 Жыл бұрын
why is time complexity of boundary traversal O(N)?? we are traversing each node more than once..
Lecture 65: Binary Tree FAANG Interview Questions || Part-3
59:15
CodeHelp - by Babbar
Рет қаралды 276 М.
Lecture 63: Binary Tree FAANG Interview Questions || Part-1
1:01:05
CodeHelp - by Babbar
Рет қаралды 423 М.
Симбу закрыли дома?! 🔒 #симба #симбочка #арти
00:41
Симбочка Пимпочка
Рет қаралды 4,4 МЛН
Transformers (how LLMs work) explained visually | DL5
27:14
3Blue1Brown
Рет қаралды 3,7 МЛН
Lecture 66: Construct a Binary Tree from InOrder/PreOrder/PostOrder Traversal
36:35
Being Competent With Coding Is More Fun
11:13
TheVimeagen
Рет қаралды 116 М.
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 834 М.
The OTHER AI Alignment Problem: Mesa-Optimizers and Inner Alignment
23:24
Robert Miles AI Safety
Рет қаралды 233 М.
Lecture 62: Binary Trees & its Representation || Different types of Traversals
55:06
Arpit Bhayani talks about real engineering for 1 hour straight
1:16:23
But what is a neural network? | Deep learning chapter 1
18:40
3Blue1Brown
Рет қаралды 17 МЛН
AIR 6 vs AIR 600 after 6 years of graduating IIT
1:12:56
Harkirat Singh
Рет қаралды 18 М.