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-codes1on12 жыл бұрын
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...
@dipuldev2482 жыл бұрын
BHAIYA QUESTION KAI BAAD USKA DRY KARWADIA KARO PLZZ SAMAJH NAHI AARAHA MAP OR QUEUE MAI KAISAI PUT KAR RAHA HAI VALUE
@harshitsharma56472 жыл бұрын
Bhaiya aaaj pakaa bol sakta hu ki Binary Tree aaaa gayi Again and Again Thankyou bhaiya 😌😌😌😌
@SatyamKumar-pd8qy2 жыл бұрын
Line 122 in vertical traversal of binary tree question. samajh nai aya. Please anyone help
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-um1oj2 жыл бұрын
ya you are right i also thought that it can solve only by using map queue
@rahulprasad35752 жыл бұрын
nice brother you gave a new perspective : )
@jayasrivastava32212 жыл бұрын
is your code acceptable on leetcode ? i am getting tle
@shubhammittal53422 жыл бұрын
@@jayasrivastava3221 its working fine
@allindiachannel22902 жыл бұрын
even i thought of that
@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 Жыл бұрын
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.
@yashmahamune87652 жыл бұрын
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😇😌💫❤🙏
@lalitsharma61322 жыл бұрын
Bhaiya aap to consistency ko dil pe le lie 😂😂
@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 Жыл бұрын
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).
@AbhishekChoudharyB8 ай бұрын
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
@divyareddy76222 жыл бұрын
Bhaiya please continue your dry runs after each question it helps sooo much!! 🥺🥺❤ thank you so muchh!!!
@delta_mohit Жыл бұрын
Khud se kar le bhai
@therealartist99 ай бұрын
@@delta_mohitkhud se krna hota to yaha ni ate na mere bhai
@delta_mohit9 ай бұрын
@@therealartist9 bhai khud se nahi karoge to kahi bhi chale jao kisi se bhi padh lo, nahi Sikh paoge dsa
@therealartist99 ай бұрын
@@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-mx9nj8 ай бұрын
@@therealartist9bhai tu 64th lecture pr hai ab dry run to khud se ho jana chahiye
@keshavgambhir98942 жыл бұрын
Present bhaiya Consistency op 🔥🔥 Attending all lectures religiously Commenting for a better reach
@suvigyabasnotra73782 жыл бұрын
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-kz2dg2 жыл бұрын
Watch his stl in 1hr video
@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 Жыл бұрын
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-vq1nm2 жыл бұрын
Consistency match kar pa raha hu or bada maza araha hai...Thanks from bottom of the heart.
@shivkumar-og4ow2 жыл бұрын
present guru ji appka to next level ki consistency hai.. aag laga diye hai🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
@alexrcrew19752 жыл бұрын
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
@utkarshpatidar1672 жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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
@anmol39 ай бұрын
No, it seems to work but it won't work
@Pawan_Sharma999 ай бұрын
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
@aditiagarwal36468 ай бұрын
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
@raviranjan34584 ай бұрын
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-oj4lm3 ай бұрын
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 ...
Such a calm and composed answer for vertical order traversal at 34:00 , best solution explanation
@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 Жыл бұрын
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 Жыл бұрын
cool
@nana_patekar_ Жыл бұрын
your answer is actually easy to understand thank you
@omkumarjha2745 Жыл бұрын
Thanks bro now the code is easy to understand.
@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).
@harshitagarg25444 ай бұрын
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.
@anjaan9372 жыл бұрын
maja aagya bhaiya , video 2 baar dekhi top view k liye lekin samj me aagya achhe se , dhnywaad aapka guruji
@HARSHSINGH-vs4ot Жыл бұрын
Coding is not difficult ' is being consistent!!
@madhabkafle80722 жыл бұрын
Answer to "College start hogaye qa ?" Roz hote he someday 8a.m -02pm Some day 10a.m - 5pm 😔😔
@KPCoder2 жыл бұрын
Thanks you sir, excellent content, no one can explain like you from basic 🙏 god bless you
@anandmaurya63842 ай бұрын
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
@adarshshrivastava4102 жыл бұрын
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.
@shiroyasha692 жыл бұрын
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 🥲
@adarshshrivastava4102 жыл бұрын
@@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.
@shiroyasha692 жыл бұрын
@@adarshshrivastava410 Yes bro sahi bola jitna time lagna hai lage DSA ko to pkka master krunga
@AmanSingh-br1nr Жыл бұрын
@@shiroyasha69 mere sath bhii aisa hi h starting phase mein yahi dikkt aati haii
@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_collections10 ай бұрын
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);
@aniketk250010 ай бұрын
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 Жыл бұрын
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
@priyanshugoyal25392 жыл бұрын
Present Bhaiya Ji Ek number consistency!❤️🔥
@harshpandey4190 Жыл бұрын
Literally I am lucky that I am following this course
@ThePrajaktaVlogs2 жыл бұрын
apki mehnat dekh ke na bhaiyya badiya sa motivation ata h ekdm 😊
@syedFAHIM-el1wr2 жыл бұрын
it is really good to see your videos without adds!
@amanaditya5602 Жыл бұрын
A big THANK YOU for starting this series really helped me a lot to strengthen my DSA skills...
@kamalshrestha341612 күн бұрын
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 Жыл бұрын
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
@suvigyabasnotra73782 жыл бұрын
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-codes1on12 жыл бұрын
haa bro sachme kaafi confusing ho gya hai btw you;re doing trees for the first time or you r revising
@suvigyabasnotra73782 жыл бұрын
@@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-codes1on12 жыл бұрын
@@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??
@suvigyabasnotra73782 жыл бұрын
@@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-codes1on12 жыл бұрын
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 Жыл бұрын
@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 😘🙏🙏🙏
@someshsangwan53022 жыл бұрын
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
@komaldewnani57472 жыл бұрын
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.
@udaypratapsingh89232 жыл бұрын
kaafi lambi soch hai aappki 😁😁😁
@justarandomguy61062 жыл бұрын
@@udaypratapsingh8923 apne to comment padh ke usko code bhi kr diya🙂
@udaypratapsingh89232 жыл бұрын
@@justarandomguy6106 dhanyavaad bhaiyaa batane ke liye
@harisrashid07732 жыл бұрын
Actually this approach can be used to solve many modifications of this particular question.
@nishanklalitjain84352 жыл бұрын
@@harisrashid0773 can you explain left view ka condition
@parthshukla43772 жыл бұрын
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-hr5my8 ай бұрын
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 Жыл бұрын
Best explanations i have ever come across on youtube. Thanks for all of these videos!
Among One of the Best videos on tree ..................Keep it up......
@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 Жыл бұрын
dry is better after every solution makes the doubt clear
@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Ай бұрын
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 Жыл бұрын
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
@prachigupta46055 ай бұрын
Nice lecture mostly best than paid course of Fraz,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
@shikharverma58242 жыл бұрын
im left behind and though in a way I want u to stop,but your consistency is on next level🔥🔥
I have a doubt at 46:00 can we insert a vector into a vector in cpp using push_back ?
@praneetdebnath71716 ай бұрын
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 Жыл бұрын
vertical order traversal was explained really well, I tried other sources but the way he explained with all the whys was appreciable.
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......
@codingarena42972 жыл бұрын
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 Жыл бұрын
There is no need to store level because nowhere it's used only horizontal distance is needed.It's added complexity to the code
@JungleKiKahaniyan82 жыл бұрын
Present hu bhaiyaa!! Maja aa raha hai And college Start ho gaye to shaam ko dekh rahe hai
@prajjawalkumarpatel9360 Жыл бұрын
Zig- Zag ki space and time complextity calculate karne ke upar video baneye-----
@shantanu8880 Жыл бұрын
In zig zac trivarsal w can also use a deque and keep a cnt of level
@dwivedi60372 жыл бұрын
Aap Meri pahle mohabat ho jise subha utha ke dekha ka man karta hai bhaiya love you ♥️♥️♥️♥️
@dwivedi60372 жыл бұрын
Bhiya aapne sab ko dil Diya hai mujhe like ap Mujhe Pyar Kam karte hai😭😭😭😭
@FanKClub Жыл бұрын
congrates bhaiya for 300k subscriber at date 31 january 2023
@sunnysingh12672 жыл бұрын
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; } };
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...
@shiroyasha692 жыл бұрын
Ab lgrha hai, computer science mere liye nhi tha 🥲, leke glti krdi ab koi option bhi bacha , padhne k alawa
@wraith3108 Жыл бұрын
how to solve question 3: vertical level in Leetcode facing issue in converting it to 2d vector?
@sarthak1391 Жыл бұрын
Awesome ! All concepts got cleared. Also solved homework question . Thanks!
@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)
@r060zeeshankhan92 жыл бұрын
// 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 Жыл бұрын
In top view, can we just print left part , right part and root?
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_blazed6 ай бұрын
For top view -> print left nodes traversal and right nodes traversal Fir bottom view -> print leaf nodes Ye concept use nhi kr skte kya ?
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; }
@nishugupta10017 күн бұрын
@@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
@paarthjindal41005 ай бұрын
At 46:00 I have a doubt can we insert a vector into a vector in cpp using push_back ?
@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 🥺🥺🥺🥺🥺
@zimstuds74302 жыл бұрын
1:10:28 kya mast padhaya🔥🔥 🔥🔥 tha apne, hint ki zarurat nhi padi
@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
@aisharawat91023 ай бұрын
What if we dont call traverseLeaf function separately for left and right subtree ...but simply for the root for once...why it wont work.
@acousticanshu936410 ай бұрын
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; } };
@priyanshisharma51157 ай бұрын
samjha gye bhai aap bhadiya tareeke se
@dep24602 жыл бұрын
College toh ho rakhe h start Bhaiya,, raat ko hi time milta h,, btw on linked list video will cover soon
@dep24602 жыл бұрын
After one month covered till this
@adityaawasthi76942 жыл бұрын
ab kidhar tak cover hogya? and konse year se ho?
@ayushrawat79512 жыл бұрын
@@adityaawasthi7694 tum konse sem ke ho bhai?
@Danish-saifi1 Жыл бұрын
@@ayushrawat7951 Kitna hua
@anjali61371 Жыл бұрын
Can you please help me how to handle college studies and this course? I always fail to handle both the things together
@avishkarpatil587110 ай бұрын
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 Жыл бұрын
map use karne get and put method O(1) mai performe ho hata hai jis se time complextiy O(N) hogi
@akashreddy7860 Жыл бұрын
Great explanation for boundary traversal
@programmer9382 жыл бұрын
Please try to explain why we are doing each step like previous videos....this video was too hard to understand
@chetansaini76442 жыл бұрын
their is no need to map element according to their level(vertical traversal).because we are already traversing by level.
@anshikasinghal5863 Жыл бұрын
why is time complexity of boundary traversal O(N)?? we are traversing each node more than once..