Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79
@ng3w4622 жыл бұрын
Bhaiya bhaiya 🤟🤟
@deepanshjohri39979 ай бұрын
Did by applying all the traversal techniques : Thanks Striver a lot 🙂 class Solution { public: void postOrder(TreeNode* root,map &mapping,int vertical,int level) { if(root==nullptr)return; if(root->left)postOrder(root->left,mapping,vertical-1,level+1); if(root->right)postOrder(root->right,mapping,vertical+1,level+1); mapping[vertical][level].insert(root->val); } void inOrder(TreeNode* root,map &mapping,int vertical,int level) { if(root==nullptr)return; if(root->left)postOrder(root->left,mapping,vertical-1,level+1); mapping[vertical][level].insert(root->val); if(root->right)postOrder(root->right,mapping,vertical+1,level+1); } void preOrder(TreeNode* root,map &mapping,int vertical,int level) { if(root==nullptr)return; mapping[vertical][level].insert(root->val); if(root->left)postOrder(root->left,mapping,vertical-1,level+1); if(root->right)postOrder(root->right,mapping,vertical+1,level+1); } void levelOrder(TreeNode* root,map &mapping) { if(root==NULL)return; queue queue; queue.push({root,{0,0}}); while(!queue.empty()) { int size=queue.size(); for(int i=0;ival); if(node->left)queue.push({node->left,{vertical-1,level+1}}); if(node->right)queue.push({node->right,{vertical+1,level+1}}); } } } vector verticalTraversal(TreeNode* root) { if(root==nullptr)return {}; map mapping; /* using preOrder Traversal preOrder(root,mapping,0,0); using inOrder Traversal inOrder(root,mapping,0,0); using postOrder Traversal postOrder(root,mapping,0,0); using level order Traversal */ levelOrder(root,mapping); vector answers; for(auto mapp:mapping) { vector answer; for(auto tt:mapp.second) for(auto inner:tt.second) answer.push_back(inner); answers.push_back(answer); } return answers; } };
@KanhaiyaLal-yv3sq7 күн бұрын
i done ,All
@ravindrabarthwal2 жыл бұрын
I'm enrolled in Coding Ninjas Competitive Programming Premium course. Your content has much more depth than CN.
@divyanshuchaudhari32572 жыл бұрын
CN is overrrrrrated
@ravindrabarthwal2 жыл бұрын
@@divyanshuchaudhari3257 the content is good but still has many shortcomings regarding platform and services.
@gowreeManohar2 жыл бұрын
@@ravindrabarthwal how much it costs?
@siddharth72612 жыл бұрын
In their CP course, they don't have any module on binary trees and binary search trees.
@Zunan2632 жыл бұрын
@@gowreeManohar don't buy man litreally even I experienced buy nothing from Coding ninjas I buyed 16k web dev course it's totally not worth even content is not there totally for a student worst platform coding ninjas
@vashishthsharma4411 Жыл бұрын
if you are solving this problem on GFG change two things 1. instead of using multiset use a vector. 2. copy the vector of vector (ans) into a 1d vector ,return the 1d vector. at last thank u Raj bhaiya , great work.
@sidarthroy815 Жыл бұрын
any reason for not using multiset?
@vashishthsharma4411 Жыл бұрын
@@sidarthroy815 on gfg we have to return a vector ,that's the reason .
@vashishthsharma4411 Жыл бұрын
@@sidarthroy815 visit this question on gfg
@MischievousSoul10 ай бұрын
One of the hardest question in the whole playlist.. Took a whole day to understand and write the code.. But ig its fair to not rush and just devote the req time to some questions..
@AppaniMadhavi4 ай бұрын
yess, I tried on my own upto some extent but wasted 6-7 hours, really amazing problem
@valdidar26 күн бұрын
took me 50 minutes of hardcore focus to solve this one, and still was only able to beat 6% all Solution time. Also had to look syntax 2 or 3 times. very difficult problem indeed.
@anonymousvoid63562 жыл бұрын
Hey everyone! Welcome back to the channel. I hope you guys are doing well! My mind gets fresh whenever i hear this from strivers mouth.
@014_anurag22 жыл бұрын
Wow after this wonderful explanation!! preorder approach became too easy. Here is the code :- void preorder(TreeNode* node,int vertical,int level,map &nodes){ if(node == nullptr) return; nodes[vertical][level].insert(node->val); preorder(node->left,vertical-1,level+1,nodes); preorder(node->right,vertical+1,level+1,nodes); } vector verticalTraversal(TreeNode* root) { map nodes; preorder(root,0,0,nodes); vector ans; for(auto p:nodes){ vector col; for(auto q:p.second){ col.insert(col.end(),q.second.begin(),q.second.end()); } ans.push_back(col); } return ans; }
@codding32world50 Жыл бұрын
CAN you explain col.insert(col.end(),q.second.begin(),q.second.end()); this line plzz bro
@sageoustheory1957 Жыл бұрын
@@codding32world50 yeah this line is confusing
@mjmusic65 Жыл бұрын
@@codding32world50 this means you are inserting all the elements of multimap at the end of the col vector
@soumikdutta78672 жыл бұрын
The GFG variant of this question is a bit easy. In the GFG variant you don't need to sort the elements, just add the elements in the ans. as it is in the tree.
@atulwadhwa192 Жыл бұрын
why can't we use inorder for the gfg probem? My Tc are not getting passed in GFG private: void preOrder(Node* node,int col,map &mp){ if(node==nullptr){ return; } if(mp.find(col)==mp.end()){ mp[col]={node->data}; } else mp[col].push_back(node->data); // or mp[col].push_back() if(node->left!=nullptr) preOrder(node->left,col-1,mp); if(node->right!=nullptr) preOrder(node->right,col+1,mp); } public: //Function to find the vertical order traversal of Binary Tree. vector verticalOrder(Node *root) { map mp; preOrder(root,0,mp); vector ans; //traverse in map and store it in ans; say ans.push_back(mp[0]) and so on..... for(auto it:mp){ // sort(it.second.begin(),it.second.end()); for(auto ele:it.second){ ans.push_back(ele); } } return ans; }
@vijaymalviya2311 ай бұрын
@@atulwadhwa192 For each vertical level, your vector should be filled from top to bottom, this thing will not happen with this code
@nopecharon2 жыл бұрын
4:37 There is a small typo, the co-ordinates of the rightmost node is actually (2, 2) not (1, 2)
@jewelchowdhury9752 Жыл бұрын
you are correct..
@dom47 Жыл бұрын
nah striver is just testing us if we are paying attention
@SomanAnshuman3 ай бұрын
@@dom47 "not a bug, but a feature" type comment 😂
@aayushgoswami86322 ай бұрын
for(auto p:nodes){ vectorcol; for(auto q:p.second){ for(int it: q.second){ col.push_back(it); } } ans.push_back(col); } use this if u didin't understood col.insert thing.
@dhanushrajan628010 күн бұрын
thanks man
@gitanjalikumari9262 Жыл бұрын
Thank you so much for explaining the C+++ code..after lot of searching I found this video and it's awesome
@iamnottech891826 күн бұрын
now I know why some said donot use java for cp ,c++ is a life saver
@cinime Жыл бұрын
Understood! Such an amazing explanation as always, thank you very much!!
@lone_wolf77212 жыл бұрын
man the explaination is masterclass.. hats off to you .. at first i have a problem but as you suggested to dry run i have done and now its crystal clear
@Dipanshutripathi24079 ай бұрын
Before wathcing the video I could not solve the problem by looking the solution but after watching video i could solve the problem on my own .
@subhamtulshan40232 жыл бұрын
Here the Time Complexity will be o(nlogN) , as we are using TreeMap and each operation in treeMap takes logN time. We can use DLL to solve it in O(N). where each node in DLL is like (data -> list of element, next -> points to the next verticle, prev-> points to the previous vertical)
@knowledgeworld6951 Жыл бұрын
Or unordered map and queue
@fahrenheit21092 жыл бұрын
absolutely amazing explanation, learned a lot more than tree traversal in this video (my STL is not the best)
@vaibhavsingh4108 Жыл бұрын
same brother
@dikshasoni52a982 ай бұрын
i think this is the hardest question of this playlist till now...... it really required like 1 day to understand this and code it.
@pranavmisra5870Ай бұрын
Brilliant explanation and hats off to whoever though of this solution.
@ishangujarathi10 Жыл бұрын
you make leetcode hard problems easy to understand!!!! tysm
@rishabhkumar81152 жыл бұрын
Got the whole approach...but struggling with the last part, which is traversing the priority queue and adding into arraylist.
@rushidesai2836Ай бұрын
Good question. Its mostly about visualizing how the node data is stored in the root map.
@vijaykumarsanugonda2784 Жыл бұрын
which data structure will be used to store the node.value,y,x in python language?
@namankeshari733211 ай бұрын
Thank you so much! This video is a life saver! Thanks again man!!
@chandrachurmukherjeejucse5816 Жыл бұрын
Solved myself without watching the solution using map of map. got a dopamine hit. Thanks striver.
@chirag6475Ай бұрын
Thank you Striver Bhaiya. You're a inspiration to me.
@Weirdvloggertrue2 жыл бұрын
Great explaination!❤️ Waiting for BSTs... 😌
@tusharnain66522 жыл бұрын
Thank you STRIVER for this amazing series, and a little bit thanks to RELEVEL.
@JohnWick-kh7ow2 жыл бұрын
Why time complexity is O(N*logn)? we are using map > So it should be O(N*logN*logN*logN). please explain.
@takeUforward2 жыл бұрын
Correct bro, i have assumed map to work as o(1) due to java
@JohnWick-kh7ow2 жыл бұрын
@@takeUforward Ok, got it.
@sans.creates2 жыл бұрын
@@JohnWick-kh7ow so what would it actually be for C++ solution?
@JohnWick-kh7ow2 жыл бұрын
@@sans.creates O(N*logN*logN*logN) will be time complexity for C++ solution. We are using two maps and one multiset and we are traversing each node.
@divyambhutani62292 жыл бұрын
Shouldnt the time complexity be same for Java because TreeMap also takes O(logn)??
@albatrossgeez66378 ай бұрын
understood.................thanks bhaiya for the amazing videos
@symbol7672 жыл бұрын
I did this in Python. I used minHeap with a tuple, I thought I had to make a class to modify/overload some minHeap functionality, but I didn't need to. So you can just use a minHeap without making a new "VerticalLevel" class class VerticalLevel: def __init__(self): self.minHeap = []; def add(self, val, level): heapq.heappush(self.minHeap, (val, level)); def remove(self): return heapq.heappop(self.minHeap); class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: result = []; queue = deque(); queue.append((root, 0, 0)); verticalHeap = {}; minLevel = float('inf'); maxLevel = -float('inf'); while len(queue) > 0: levelSize = len(queue); for _ in range(levelSize): node, level, vertical = queue.popleft(); minLevel = min(minLevel, vertical); maxLevel = max(maxLevel, vertical); if vertical not in verticalHeap: verticalHeap[vertical] = VerticalLevel(); verticalHeap[vertical].add(level, node.val) if node.left: queue.append((node.left, level + 1, vertical - 1)); if node.right: queue.append((node.right, level + 1, vertical + 1)); for level in range(minLevel, maxLevel + 1): print(level) currentLevel = verticalHeap[level]; # Pop all elements off the modified minHeap and add it into a tempLevel array tempLevel = []; while len(currentLevel.minHeap) > 0: level, value = currentLevel.remove(); tempLevel.append(value); # Now append the tempLevel array into the result array result.append(tempLevel); return result;
@sudhanshukumar33912 жыл бұрын
I understand this question partially. When i understand the problem statement , then at same moment I guessed that this problem would be leetcode hard category, And yes it is.
@shreyasharma7987 Жыл бұрын
What is the significance of storing the level? we can just use the vertical indexing to store the elements.
@stylewithsmriti2 жыл бұрын
This approach takes O(n*logn) time complexity. Can you please make a video on efficient solution that takes O(n)?
@jashanbansal26132 жыл бұрын
Can be solved using map We r going level by level only, so nodes would be inserted from top to bottom, therefore no need to maintain level
@takeUforward2 жыл бұрын
Vector will distort the sorted wala property..
@jashanbansal26132 жыл бұрын
@@takeUforward We r going level by level, first it will push_back node at level 0, then for level 1, then for level 2 and so on.. So by default it's in order. U can check it once again, otherwise I will post code tomorrow
@takeUforward2 жыл бұрын
@@jashanbansal2613 if in the same vertical, and same level you have 9 first and then 8, your vector will store 9,8 But should be 8,9 :)
@jashanbansal26132 жыл бұрын
@@takeUforward Thanks for taking time to reply Man :)
@AyushGupta-kp9xf2 жыл бұрын
@@takeUforward bhaiya if we iterate from backwards while traversing in the map finally, will that work ?
@codeman38283 ай бұрын
Understood. Great video
@darshansurana73312 жыл бұрын
In this video The time Complexity is (Addition of LogN)-> O((LogN + LogN + LogN) * N) and not (Multiplication of LogN)-> O((LogN * LogN * LogN) * N) first LogN for first map, second LogN for second map and third LogN for the multiset and this is done for all N elements so multiply by N. Am I Correct ?
@mriduljain1981 Жыл бұрын
i did the 90% question myself i just couldnot find out which datastructure to use i am super happy about it ..................
@AdityaKumar-be7hx Жыл бұрын
Could we have just used "mapint>> nodes"?
@Pooja-lm5yj3 ай бұрын
it's not allowed because std::map keys must be of a type that supports comparison for equality and ordering.
@Progamer-fq8st11 ай бұрын
We can also use map
@bestdeal33852 жыл бұрын
for those having difficulty in the last part can use this code segment ( just elaborated a bit for easy understanding ) 😊😊 vector ans; for(auto it:m) { vector v; for(auto t:it.second) { for(auto x:t.second) { v.push_back(x); } } ans.push_back(v); } return ans; }
@jaspreetmehra5722 жыл бұрын
mapnodes; nodes[x][y].push_back(head->data); Can you explain how the value is getting stored? I am not getting how this statement "nodes[x][y].push_back(head->data);" is working internally? TIA
@madhabkafle88982 жыл бұрын
@@jaspreetmehra572 if you use this statement then the node will get inserted in its (vertical,level) , u might not understand what i have typed xD, but once visualise x and y ...x=p.second.first ,y=p.second.second ,u might understand
@jerryraphy7392 жыл бұрын
@XanderSRАй бұрын
This code is wrong bro. It will include values with same level and vertical but doesn't include values with same vertical and different levels in a same array.
@Negijicoder14 күн бұрын
i've done it myself by using bfs(level order) and preorder..(dfs, and used tuple to store all values.. like vector vec; )
@naro.tam_2 жыл бұрын
What a great explanation 🙏🙏🙏🙏🙏
@Ramu91197 ай бұрын
Nice Explanation
@shivanisisodia6189 Жыл бұрын
thankgod first time he has taken Queue diagram as a queue not as a stack like in other videos, there is so much confusion bcoz of that and difficult to remember also for future.
@ritikshandilya70752 ай бұрын
superb explanation
@peter9759 Жыл бұрын
Lovely explanation yaar itne pyaar se kisi ne nhi sikhaaya
@user-lg1vw7hc1gАй бұрын
can we solve this qs without level and just by using vertical, node ?
@sriharithakancharla54437 ай бұрын
in c++ code line 24 why should we use insert y not push_back?
@sahilgupta92632 жыл бұрын
why we are inserting q.second using col.end() in col.insert(col.end(),q.second,begin(),q.second.end()) ?
@ganeshjaggineni409710 күн бұрын
NICE SUPER EXCELLENT MOTIVATED
@harshdeepak32812 жыл бұрын
hey striver why col.push_back didnt worked in case of vector here?? why we used insert function?
@Gaurav-fb9ds Жыл бұрын
vector < vector < int >> ans; for (auto p: nodes) { vector < int > col; for (auto q: p.second) { col.insert(col.end(), q.second.begin(), q.second.end()); } ans.push_back(col); } Can someone explain this?
@shubhamagrawal22124 Жыл бұрын
Suggest you to keep meaningful variable names. Anyways thanks for all your content, really helpful.
@bhashkarbelwal41165 ай бұрын
what an easy clarification yar man
@harish5466 Жыл бұрын
why cant we use datastructure like map?
@karankapoor61452 жыл бұрын
In c++ code line no. 26 , how are we making sure that when two or more complete multiset items are inserted in a column , the column will have sorted elements? Multisets contain sorted elements but when two or more multiset contents are pushed into a vector one after the other, the resulting vector might not be sorted.
@herculean6748 Жыл бұрын
Can someone please explain this a bit (Inner for loop, how many times will it run) for (auto p: nodes) { vector < int > col; for (auto q: p.second) { col.insert(col.end(), q.second.begin(), q.second.end()); } ans.push_back(col); }
@rishabhgupta9846 Жыл бұрын
for (auto q: p.second) will run number of horizontal levels we have whereas col.insert(col.end(), q.second.begin(), q.second.end()) will insert number of elements which are present on [vertical level] [horizontal level]
@rishabhgupta9846 Жыл бұрын
can also do this way vector res; for (auto itr1 = nodes.begin(); itr1 != nodes.end(); itr1++) { vector temp; for (auto itr2 = itr1->second.begin(); itr2 != itr1->second.end(); itr2++) { for (auto itr3 = itr2->second.begin(); itr3 != itr2->second.end(); itr3++) { temp.push_back(*itr3); } } res.push_back(temp); } return res;
@saisaran42149 күн бұрын
hey striver could you please explain the time complexity a clear for this im not getting
@user-tk2vg5jt3l4 ай бұрын
Thank you Bhaiya
@anmolswarnkar77072 жыл бұрын
I was able to solve this one myself, but instead of using multisets, I sorted the individual columns later (based on the values of nodes on the same level).
@tharundharmaraj9045 Жыл бұрын
Can u pls share?
@DimensionalDriftYoru Жыл бұрын
@@tharundharmaraj9045 I did the similar thing void preorder(TreeNode* root,int curr,int ver,unordered_map &m){ if(!root) return; m[curr].push_back({ver,root->val}); preorder(root->left,curr-1,ver+1,m); preorder(root->right,curr+1,ver+1,m); } vector verticalTraversal(TreeNode* root) { unordered_map m; preorder(root,0,0,m); vector v; for(auto i:m){ v.push_back({i.first,i.second}); } sort(v.begin(),v.end()); vector ans; for(auto i:v){ vector temp; sort(i.second.begin(),i.second.end()); for(auto j:i.second){ temp.push_back(j.second); } ans.push_back(temp); } return ans; }
@Satyendra_Prakash172 ай бұрын
my saved notes are not showing in atoz sheet. And on opening it from saved notes on website , the notes are not correctly placed like how i had originally wrote it and some content from it is also missing . If Anyone knows how to fix it please help.
@surbhirathore._Ай бұрын
Understood ❤❤
@kotipallimadhumeher712 жыл бұрын
can anyone tell me why he was changing the row instead of verticals/col ?
col.insert(col.end(), p.second.begin(), p.second.end()); please explain this line
@shauryashekhar2 жыл бұрын
@@sawantanand3681 basically you are adding at the end of your vector "col" map.first.begin ie say you have an element {1,2} in the map inside the outer map you declared...then map.first.begin refers to 1 and map.first.end refers to 2. Alternatively you can do it this way if you want for(auto q: p.seond) //so q refers to your multiset now while p was referring to your map above. {col.push_back(q)}; } ans.push_back(col); } return ans; } };
@virusdgamer8804 Жыл бұрын
@@shauryashekhar what if there is only 1 element on a level and not two? will the map.first.begin and map.first.end both not print the same value twice because both the pointers will be on the same value?!?
@RahulSingh-vv9jj2 жыл бұрын
Awesome Explanation Bhaiya
@firdouszoyakhan940416 күн бұрын
instead of multiset can we use vector?
@sharmaklonde6892 жыл бұрын
here on line 24 why do we give the position as col.end() ? plzz someone explain
@suryamanisudhakar57432 жыл бұрын
if(node->left) q.push({node->left,{x-1,y+1}}); While pushing the updated position of vertical and level in the queue I am using x-- and y++ in the place of x-1 and y+1(for both left and right node). But It is giving me the wrong answer. Can somebody help me out.
@shubhamaswal19932 жыл бұрын
you should use - - x and ++y
@lifehustlers16411 ай бұрын
Completed 22/54(40% done) !!!
@nikharbehera56135 ай бұрын
we can also use map> nodes where nodes.first will represent vertical lines and multiset stores all the corresponding nodes (no need to keep track for level) am i right ??
@XanderSRАй бұрын
No because at time of insertion you need to maintain level also and there can be more than one values of vertical lines at a particular level.
@111rhishishranjan2 Жыл бұрын
I was saying if let say we take down with -ve y axis of for node value 2 , we must store (2,-1,-1) .
@ravalikatalks52856 ай бұрын
thanks alot!
@codingp110Ай бұрын
understood!
@amartyapatil41242 жыл бұрын
@take U forward you need to make change in java tuple and code since we need to sort the priorityQueue based on y not based on x Here iscode with changes. class Tuple{ TreeNode node; int row; int col; public Tuple(TreeNode _node,int _row,int _col){ this.node=_node; this.col=_col; this.row=_row; } } class Solution { public List verticalTraversal(TreeNode root) { TreeMap map=new TreeMap(); List vertical=new ArrayList(); Queue q=new LinkedList(); q.offer(new Tuple(root,0,0)); while(!q.isEmpty()){ Tuple tuple=q.poll(); TreeNode node=tuple.node; int x=tuple.col; int y=tuple.row; if(!map.containsKey(x)){ map.put(x,new TreeMap()); } if(!map.get(x).containsKey(y)){ map.get(x).put(y,new PriorityQueue()); } map.get(x).get(y).add(node.val); if(node.left!=null){ q.offer(new Tuple(node.left,y+1,x-1)); } if(node.right!=null){ q.offer(new Tuple(node.right,y+1,x+1)); } } for(TreeMap ys:map.values()){ vertical.add(new ArrayList()); for(PriorityQueue nodes:ys.values()){ while(!nodes.isEmpty()){ vertical.get(vertical.size()-1).add(nodes.poll()); } } } return vertical; } }
@coding8000 Жыл бұрын
Understooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooood, Ctr + right arrow, for shifting the chapter of ads in video
@lexeve5298 Жыл бұрын
void vertical(TreeNode*root,int d,map&map){ if(root == nullptr) return; map[d].push_back(root->val); vertical(root->left,d-1,map); vertical(root->right,d+1,map); return; } this just dont cover the ascending order of 2 nodes at same level and line, can anybody help me?
@harshbhagwani77692 жыл бұрын
PYTHON SOLN FOR VERTICAL ORDER TRAVERSAL class Solution: def __init__(self): self.values={} def vertical_order(self,root,x,y): if root is None : return if x in self.values : self.values[x].append((y,root.val)) else : self.values[x]=[(y,root.val)] self.vertical_order(root.left,x-1,y+1) self.vertical_order(root.right,x+1,y+1) def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: self.vertical_order(root,0,0) result=[] for x in sorted(self.values.keys()): column=[i[1] for i in sorted(self.values[x])] result.append(column) return result
@mayurbhor22312 жыл бұрын
The problem can be solved in O(N) time without multiset , if the order of overlapping elements is not necessary to be in ascending order
@adityasai5502 жыл бұрын
Yeah I think then we just need to use map
@tushar7305 Жыл бұрын
What is order of overlapping ?
@siddharthsaxena64952 жыл бұрын
In GFG they are taking map instead of map. Can u please tell me why and whats the difference??
@takeUforward2 жыл бұрын
It won’t store sorted na if on a level there are multiple overlap.
@kanhaiyatulsyan75602 жыл бұрын
i think they are not storing level also they are only storing vertices(-1,0,+1..) and the nodes at respective vertices
@nagavedareddy58912 жыл бұрын
Huge respect...❤👏
@nischayagrawalVlogs10 ай бұрын
at 1:30 , How come 1 , 10 , 9 and 6 are overlapping. I mean I just don't understand, aren't they all in different vertical line??
@SumitKeshariMCS Жыл бұрын
Solved on my own. Then watched your video. Thanks striver for quality content. here is my code: class Solution { public: vector verticalTraversal(TreeNode* root) { vectorans; if(root==NULL) return ans; queueq; q.push({0,{0,root}}); mapmp; while(!q.empty()) { auto it = q.front(); q.pop(); int hd = it.first; int level = it.second.first; TreeNode* node = it.second.second; mp[hd][level].insert(node->val); if(node->left) q.push({hd-1,{level+1,node->left}}); if(node->right) q.push({hd+1,{level+1,node->right}}); } for(auto it = mp.begin();it!=mp.end();it++) { vectortemp; for(auto i = it->second.begin();i!=it->second.end();i++) { for(auto ii = i->second.begin();ii!=i->second.end();ii++) { temp.push_back(*ii); } } ans.push_back(temp); } return ans; } };
@vakhariyajay2224 Жыл бұрын
Thank you very much. You are a genius.
@janhavitripurwar92932 жыл бұрын
Is this TC CORRECT ? TC :O(N) {For queue loop} + O(h * (2^h)-1) {for map traversing loop} {h=height of BT}
@architarora-iiitd32652 жыл бұрын
Just check once that in line 12, it should be nodes[y][x]
@suryaer33692 жыл бұрын
but why didnt we "loop" the levels ? whats the difference ?
@ApnaVlogs-tj7do9 ай бұрын
Legend ❤🔥
@noobchess25168 ай бұрын
easy solution that you can understand using custom data structure . idea - custom datastructure to store node value, x,y coordinate and then sort it as per our required . (sort in termss of x coordinate if same, sort in terms of y coordinate, if same ,value compare all in ascending order) then just return vector. struct point{ int value; int x; int y; }; void travel(TreeNode*root,int x,int y,vector&save){ if(root==NULL){ return; } point a ; a.value=root->data; a.x =x; a.y=y; save.push_back(a); travel(root->left,x-1,y+1,save); travel(root->right,x+1,y+1,save); } bool compare(point a,point b){ if(a.x!=b.x){ return a.x
@utkarshsharma66502 жыл бұрын
a bit difficult, but still understood :-/ will come back on it again
@ShivamKanojia-oz8phАй бұрын
Using Inorder class Solution { public: void traversal(TreeNode* root, int vertical, int level, map &nodes) { if (root == NULL) return; traversal(root->left, vertical - 1, level + 1, nodes); nodes[vertical][level].insert(root->val); traversal(root->right, vertical + 1, level + 1, nodes); } vector verticalTraversal(TreeNode* root) { vector ans; map nodes; traversal(root, 0, 0, nodes); for (auto i : nodes) { vector col; for (auto j: i.second) { col.insert(col.end(), j.second.begin(), j.second.end()); } ans.push_back(col); } return ans; } };
@rohangangwar66042 жыл бұрын
bhaiya we are storing values in maps of maps + multiset .. why we don't added the time and space complexity of maps of maps as well??
@takeUforward2 жыл бұрын
Usually hashmap works in o(1) in java, hence i said you can compute map wala khud se depending on language you using.
@lavanyaprakashjampana933 Жыл бұрын
we love your content and we love you....🖤
@prateekchauhan53762 жыл бұрын
why are we adding in the end of the list in last code of java?
@subodh.r48352 жыл бұрын
Extremely easy explanation for a leetcode hard level question!
@oyesaurabh Жыл бұрын
Doubt : In the last part //This is correct for(auto it:mp){ //vertical vector col; for(auto i:it.second) //level col.insert(col.end(), i.second.begin(), i.second.end()); ans.push_back(col); } //But why not this....why cant I use push_back in vector instead of " col.insert(col.end()...) " ??? for(auto it:mp){ //vertical vector col; for(auto i:it.second) //level col.push_back( i.second.begin(), i.second.end()); ans.push_back(col); }
@kumkummittal7270 Жыл бұрын
col is having data type as int and not that of any 1d vector or set, we cannot pushback
@taukirkhatri33682 жыл бұрын
I have some confusion regarding the time complexity! My thoughts on time complexity are: One thing to note here is that the multiset for a vertical level V and horizontal level H will store at max 2 node values. This is because we know that at max there can be two guys with same vertical and horizontal level as the given tree is binary tree. So the complexity for maintaining the multiset can be ignored. Now, what about the vertical and horizontal level? At max the vertical level i.e. the max width of the binary tree in the worst case can be 2^H - 2^(H-1) which can be considered as 2 ^ H in the case of perfect binary tree, and the max value of horizontal level would be the height of the tree which is H. Now we know the max values for vertical and horizontal levels. To maintain the map of vertical levels we require log(2 ^ H) (base 2) time and to maintain the inner map of horizontal levels we require log(H) time. So, in total the time complexity would be O(N * H * log(H)) where N is for the traversal of the tree. P.S: Please correct me if I'm wrong
@shaileshsingh6771 Жыл бұрын
bhai 2 se jada values bhi ho skti hai ek vertical pe
@mohit7717Ай бұрын
I am not able to unserstand one thing that how section in code is working:_ col.insert(col.end(), q.second.begin(), q.second.end()); ``` vector ans; for(auto p: nodes){ vector col; for(auto q: p.second){ // Insert node values // into the column vector col.insert(col.end(), q.second.begin(), q.second.end()); } // Add the column vector // to the final result ans.push_back(col); } return ans; ```
@tanaysingh5348 Жыл бұрын
thanks for such quality content
@aishwaryamajumdar69272 жыл бұрын
Shouln't the x be vertical and y the level? You have take x = tuple.row but should have been the column/vertical.