Vertical Order Traversal of a Binary tree (Algorithm)

  Рет қаралды 71,891

Vivekanand Khyade - Algorithm Every Day

Vivekanand Khyade - Algorithm Every Day

Күн бұрын

Пікірлер: 147
@prasannachalgeri7152
@prasannachalgeri7152 6 жыл бұрын
Vivekanand - Very nice.. I guess if we watch all your videos "many times" then any one could crack any DSA interviews.. There are books in market but they are not as sweet as your explaination.
@mp0157
@mp0157 5 жыл бұрын
It is very difficult to keep a topic simple and yet make it so effective for the audience! You have achieved both! Thank you Vivekanand! This video was very helpful!
@rainegreen4687
@rainegreen4687 4 жыл бұрын
Very clear explanation! This is the first time I watched your video, will surely look for more of these.
@abhishekgautam1063
@abhishekgautam1063 5 жыл бұрын
Everything is so nicely explained! Please continue making videos covering maximum topics and fields. Thanks
@Blingblingblingling
@Blingblingblingling 6 жыл бұрын
video is nicely done. thank you. using any tree traversal should work, filling hash table during traversal. no need for a queue for BFS.
@aiswaryajami2841
@aiswaryajami2841 3 жыл бұрын
Understood the algo in less than 2mins... you are awesome. thank you!!
@sachinkulkarni9108
@sachinkulkarni9108 4 жыл бұрын
Hi Vivekanand, The video is really nice and easy to follow. Just one question though.... in the algorithm you described, when we deque the nodes, how are we supposed to get their horizontal distance (h.d.) which is needed to update the h.d. of the left and right child nodes. We can't use the hash table mentioned as the key there is the h.d. and the value is the tree node. So, we can't lookup in the hash table with the node as the key. Wouldn't we need another hash table or some other mechanism to query the h.d. of a given node?
@amulyareddyg9290
@amulyareddyg9290 4 жыл бұрын
maybe we can use a queue of pairs of .root's hd is 0 .whenever we deque a node from the queue ,we enqueue its children .So while enqueuing left child it's hd will be one less than its parent node (which we just dequed ..so we already know its hd) similarly when we enqueue its right node its hd is one greater than the parent
@sekharbarua839
@sekharbarua839 4 жыл бұрын
Vivekanand - How do you remmember all the algo.. It is really nice .. I have followed your video and implement the same using Python..
@umeshgidnavar8196
@umeshgidnavar8196 6 жыл бұрын
Thanks for very good explanation. I have added code for the same for other people who want code for this algorithm. Current algorithm calculates sum of vertical column order. If just want to display vertical column order then with simple change in code we can achieve that. Thanks. import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; public class VerticalTraversalAndVerticalSum { // From root left child will have parent-1 value for horizontal distance and right child will have // parent+1 horizontal distance. Add them in hashmap checking if it is already there in hashmap // then add values or add new entry public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); Util.printTreeInOrder(root); System.out.println(); Map inOrderColumnSumMap = new HashMap(); findVerticalSumInorderTraversal(root, 0, inOrderColumnSumMap); System.out.println("Vertical column sum using Inorder traversal: " + inOrderColumnSumMap); Map leverOrderColumnSumMap = new HashMap(); findVerticalSumLevelOrderTraversal(root, leverOrderColumnSumMap); System.out .println("Vertical column sum using Lever order traversal: " + leverOrderColumnSumMap); } private static void findVerticalSumLevelOrderTraversal(TreeNode root, Map leverOrderColumnSumMap) { Queue q = new LinkedList(); q.add(root); Map columnValueMap = new HashMap(); columnValueMap.put(root, 0); while (!q.isEmpty()) { TreeNode current = q.poll(); int currentColumnValue = columnValueMap.get(current); if (leverOrderColumnSumMap.containsKey(currentColumnValue)) { leverOrderColumnSumMap.put(currentColumnValue, leverOrderColumnSumMap.get(currentColumnValue) + current.data); } else { leverOrderColumnSumMap.put(currentColumnValue, current.data); } if (current.left != null) { q.add(current.left); columnValueMap.put(current.left, currentColumnValue - 1); } if (current.right != null) { q.add(current.right); columnValueMap.put(current.right, currentColumnValue + 1); } } } // Using inorder keep adding horizontal distance and add sum to Map private static void findVerticalSumInorderTraversal(TreeNode root, int column, Map columnSumMap) { if (root == null) { return; } if (columnSumMap.containsKey(column)) { columnSumMap.put(column, columnSumMap.get(column) + root.data); } else { columnSumMap.put(column, root.data); } // Left child parent-1 as column value findVerticalSumInorderTraversal(root.left, column - 1, columnSumMap); // Right child parent+1 as column value findVerticalSumInorderTraversal(root.right, column + 1, columnSumMap); } } public class TreeNode { public E data; public TreeNode left; public TreeNode right; public TreeNode(E data) { this.data = data; } @Override public String toString() { return "data: "+data; } } public class Util { public static void printTreeInOrder(TreeNode node){ if(node != null){ printTreeInOrder(node.left); System.out.print("["+node.data+"], "); printTreeInOrder(node.right); } } }
@prateektripathi100
@prateektripathi100 5 жыл бұрын
This guy is better than many of the useless books available in the market....hats off to you
@deepakpai1893
@deepakpai1893 4 жыл бұрын
I saw a lot of solutions for this question, but yours explained it very well. Thanks.
@shreyasmahajan5291
@shreyasmahajan5291 3 жыл бұрын
@Vivekanand Khyade - Algorithm Every Day bhai tuch aapla dada, thank you great explanation!!]
@agniswarbakshi7961
@agniswarbakshi7961 7 жыл бұрын
nice explanation, thanks for the video..please upload some on dynamic programming too :)
@vivekanandkhyade
@vivekanandkhyade 7 жыл бұрын
Thanks Agniswar......yes i will upload videos on dynamic programming..!
@andreyklysheiko500
@andreyklysheiko500 6 жыл бұрын
in order to print it there's on more step - order by ascending, because if you print as is you will get a, e, f, b, i, j, c, k, d, g, h, l instead of h, d, b, i, j ..... and so on
@akshaybangar7070
@akshaybangar7070 6 жыл бұрын
ist's best algo video because you solve problems in easy way.Thanks sir
@vivekgr3001
@vivekgr3001 4 жыл бұрын
Thanks for excellent explanation! walking through the algorithm line by line!
@YogeshKumar-px5bd
@YogeshKumar-px5bd 3 жыл бұрын
Why he has so less subscribers just because he's teaching in an old typical way. No way He definitely deserves subscriber and really good content.
@rajeshsingh-mv7zn
@rajeshsingh-mv7zn 2 жыл бұрын
Because these are old videos. He stopped uploading regularly and reach went down
@chaitu10552
@chaitu10552 5 жыл бұрын
your explanation covers everything. easy to understand. Thanks
@saileshverma7353
@saileshverma7353 3 жыл бұрын
Awesome explanation bhaya
@MohsinKhan-sg8wq
@MohsinKhan-sg8wq 5 жыл бұрын
You Made it very easy to understand using Level order traversal.. Thank you.. But writing code for this approach is more complex because whenever you dequeue an element you need to know the HD value of that node which is not available at the time of getting node from queue. OR I am missing something ?? This can be very easy using recursion.
@saurabhvemuri5323
@saurabhvemuri5323 5 жыл бұрын
In CPP, You can use queue q; This will store node and its level
@shrabanakumar7754
@shrabanakumar7754 5 жыл бұрын
Sir really helpful videos. I have a request, please categorize the videos which will be helpful to go through based on topics .
@785_barneetpanda5
@785_barneetpanda5 4 жыл бұрын
If you could add the code along with explanation, it helps a lot
@pradeepanand5296
@pradeepanand5296 5 жыл бұрын
First time watching... Man, u r awesome
@MYUCOZ1
@MYUCOZ1 6 жыл бұрын
You can also do this with Pre Order traversal of tree. No need to use Queue as extra storage. Good explanation.
@every_instant
@every_instant 5 жыл бұрын
Pre Order travelsal + Hash will hav reverse vertical results. Therefore, to achieve top down vertical traversal (higher level nodes appear 1st) we need to traverse by level order.
@mridulmanohar5940
@mridulmanohar5940 6 жыл бұрын
Horizontal distance, Hd of each node is stored in the node itself or where? because we need the parent node's HD to compute HD for left or right child node so in a iterative loop it won't work with a local or global variable.
@dewdropk-dl5tv
@dewdropk-dl5tv 6 жыл бұрын
while insertng in the queue, insert with the hd, (object with node and hd for it)
@saurabhvemuri5323
@saurabhvemuri5323 5 жыл бұрын
In CPP, You can use queue q; This will store node and its level
@SatishKanaujiyaeb
@SatishKanaujiyaeb 4 жыл бұрын
Very nice maza aa gya !!!
@argharoy6571
@argharoy6571 4 жыл бұрын
Excellent explanation
@quangluong5413
@quangluong5413 4 жыл бұрын
Is this possible to use preorder traversal instead of level-order traversal? My reason is because the algorithm is based on the horizontal distance of the root node to calculate for children node (which is why inorder, postorder are irrelevant)?
@vinodrammohan
@vinodrammohan 3 жыл бұрын
Very good explanation. However it would be better if you list the data structures that we would need to create in order to implement this solution. For example, it was not obvious that we need to create a new data structure to store the tree node along with its Hd.
@PrinceKumar-eb8hd
@PrinceKumar-eb8hd 6 жыл бұрын
sir, here we don't know the size of hash table so it varies from (n-1) to -(n-1), this increases the space complexity, moreover, u are inserting the values at the end in the hash table which results in the increase in time complexity. instead of inserting values in last we can insert at the beginning of the node. is there any approach i.e any dynamic implementation using doubly linklist
@pawandeepchor89
@pawandeepchor89 6 жыл бұрын
Awesome, you guys are so cool !! Keep going !!
@suchitragiri4546
@suchitragiri4546 4 жыл бұрын
Very nice explained sir!!
@SiddDev
@SiddDev Жыл бұрын
hii,thnks for this easy explanation kindly do upload videos on dynamic programming also ....
@Shashi0012
@Shashi0012 4 жыл бұрын
Do hashtables allow storing same keys? as you are using hd as the key but multiple nodes have the same hd.
@ivyxue6443
@ivyxue6443 3 жыл бұрын
very good explanation!! Thank you
@abhishekmulay
@abhishekmulay 7 жыл бұрын
Thank you Vivekanand. This is a really good explanation for this problem. I have one question, why not insert the nodes in a dictionary/map while traversing the tree instead of using Queue?
@every_instant
@every_instant 5 жыл бұрын
we need to queue up nodes so that we can traverse by level order. Other traversal algo which dont required queue such as preorder traversal, will yield reverse vertical results
@parthsoni7370
@parthsoni7370 3 жыл бұрын
Great Explanation! Thanks
@aanchalsharma5264
@aanchalsharma5264 4 жыл бұрын
U deserves to have lakhs of views Keep going and thanks
@EternalEntity01
@EternalEntity01 6 жыл бұрын
please upload algorithms for m-way search tree and its different operation. your explanation is very nice.thanking u for this great job
@saurabhverma3453
@saurabhverma3453 4 жыл бұрын
From where you are getting HD of dequeque nodes. Means when you de-queque B, how did you know that HD value for B is -1. You didn't store it anywhere, you are directly calculating it from diagram, but in programming we need to store it somewhere or not?
@nikhilm4290
@nikhilm4290 4 жыл бұрын
If you do Level order traversal using DFS, then there you can use HD variable as a parameter in recursion. Just wondering how it can be done in BFS.
@nikhilm4290
@nikhilm4290 4 жыл бұрын
The idea is to make (node, HD) a pair... www.geeksforgeeks.org/print-a-binary-tree-in-vertical-order-set-3-using-level-order-traversal/
@saurabhverma3453
@saurabhverma3453 4 жыл бұрын
@@nikhilm4290 level order traversal using DFS, what does it mean? DFS is for depth search not level. Can u explain it?
@saurabhverma3453
@saurabhverma3453 4 жыл бұрын
@@nikhilm4290 yeah thats what I commented that we need to store HD value of nodes.
@namrataojha9123
@namrataojha9123 7 жыл бұрын
Nicely explained !!! Could you please cover some videos on dynamic programming ?
@hussainsaifygaming
@hussainsaifygaming 7 жыл бұрын
Vivekanand your explanation was very good. I would like to know the code implementation of the above algorithm because the one which I have implemented is with the recursion. Want to know both the ways. Thanks in advance.
@muditmanchanda1062
@muditmanchanda1062 6 жыл бұрын
can you please mail me
@travelogue4566
@travelogue4566 7 жыл бұрын
thank so much for nice explanation , great work and keep adding more video .
@keyurshah5203
@keyurshah5203 4 жыл бұрын
Nice explaination - easy to implement
@successally
@successally 4 жыл бұрын
Nicely explained thank you sir🙏
@arun26cs
@arun26cs 5 жыл бұрын
yes vivek you are super explainatory!!!!!
@ok123ut
@ok123ut 4 жыл бұрын
Amazing explanation!
@richa6695
@richa6695 4 жыл бұрын
What is the most intuitive answer to this question
@smayengbam
@smayengbam 5 жыл бұрын
Thank you Sir. Well explained. I salute you 👍
@bhupalibaishya2136
@bhupalibaishya2136 6 жыл бұрын
it's really very nice video and the explanation is so so awesome sir !
@ruchimishra2805
@ruchimishra2805 7 жыл бұрын
very nice explanation.keep them coming
@GauravKawatrakir
@GauravKawatrakir 3 жыл бұрын
is it work for "Vertical Order Traversal of a Binary Tree | leetcode 987' ??
@Vj-nu5vx
@Vj-nu5vx 6 жыл бұрын
please upload algorithms for graph
@harryinsin
@harryinsin 5 жыл бұрын
I don't think there is a strict need for level order traversal. A simple recursive inorder traversal would suffice.
@shreeshametkari7963
@shreeshametkari7963 7 жыл бұрын
Nice one Sir..
@vivekanandkhyade
@vivekanandkhyade 7 жыл бұрын
Thanks Amol Bhai...kasa aahes??
@prashantsrivastava9550
@prashantsrivastava9550 3 жыл бұрын
good explanation...thnx
@mdsaif4696
@mdsaif4696 7 жыл бұрын
Bhaiya code de do...
@arhamzayed8322
@arhamzayed8322 7 жыл бұрын
Vivekanand Khyade, thank you for nice explanation.
@vivekanandkhyade
@vivekanandkhyade 7 жыл бұрын
Thanks Arham.
@ArpitDhamija
@ArpitDhamija 4 жыл бұрын
there are difficult codes available on google , please upload a simple code here......
@DeepakPandey
@DeepakPandey 7 жыл бұрын
Hi @vivekanand thanks for explanatory videos. Could you please cover trie data structures and there applications. Thanks in advance !
@vivekanandkhyade
@vivekanandkhyade 7 жыл бұрын
Thanks Deepak...video on trie data structure is coming soon...!
@DeepakPandey
@DeepakPandey 7 жыл бұрын
thanks @Vivekanand ... great videos..
@VivekSingh-vi3cd
@VivekSingh-vi3cd 6 жыл бұрын
We have to sort by key to get the final result.
@Amazi007
@Amazi007 5 жыл бұрын
why not use a TreeMap?
@piyushjha7222
@piyushjha7222 5 жыл бұрын
sir how to update hd and its corresponding pair in map??
@zenshyam
@zenshyam 4 жыл бұрын
The explanation is very good and I am able to understand it too...But i am unable to code that in java....Can someone help me with it.....Thanking you in advance..
@TheMihirthakkar
@TheMihirthakkar 4 жыл бұрын
Thanks for making this video. It helped me a lot :)
@karansingh-kp3xg
@karansingh-kp3xg 5 жыл бұрын
Whoever asking code, did you ever google "vertical order traversal of binary tree"?
@hellostar3063
@hellostar3063 4 жыл бұрын
how to create a hash table
@JithendrakumarK
@JithendrakumarK 4 жыл бұрын
@@hellostar3063 Since the KEYS we are going to store are unique, we can use unorderdMap here, which stores the unique values and it will not sort either.
@tatianazihindula8762
@tatianazihindula8762 6 жыл бұрын
at 4:43, what if node 'f' had a left child?? its child's horizontal distance could have been -1 too. any comment on this?
@MYUCOZ1
@MYUCOZ1 6 жыл бұрын
Yes
@ankitaverma2271
@ankitaverma2271 4 жыл бұрын
This video really helped me..
@ANJALIGUPTA-vq1cv
@ANJALIGUPTA-vq1cv 2 жыл бұрын
u r awesome sir
@amitpadaliya6916
@amitpadaliya6916 5 жыл бұрын
any idea how to put more than one value in hashmap in java
@ayaan_faiz
@ayaan_faiz 7 жыл бұрын
Great Explanation. Understood it properly. +1 Subscriber. Thanks
@sanaullah-wu4ww
@sanaullah-wu4ww 4 жыл бұрын
very helpful. Thank you!
@ashvinsrivastava7378
@ashvinsrivastava7378 4 жыл бұрын
well done sir
@ayushthakur733
@ayushthakur733 4 жыл бұрын
Telephone rings at 8:35 😂😂😂😂
@TheUmar26
@TheUmar26 4 жыл бұрын
how to get HD of root in while loop so that can add HD for left and right child ??
@prashantnagrurkar2784
@prashantnagrurkar2784 5 жыл бұрын
Thank you! Sir.
@javi2082
@javi2082 4 жыл бұрын
Hey, the video is nice. Just a suggestion. Please start first with explaining what the question and concept is.
@effy1219
@effy1219 7 жыл бұрын
very clear drawing
@vivekanandkhyade
@vivekanandkhyade 7 жыл бұрын
Thanks effy..!
@nandinichouta4119
@nandinichouta4119 6 жыл бұрын
Can you please let us know what are the time and space complexity
@saurabhvemuri5323
@saurabhvemuri5323 5 жыл бұрын
TC:O(N), SC:O(N)
@abhishekjain8869
@abhishekjain8869 5 жыл бұрын
awesome veere
@jiangyucara
@jiangyucara 5 жыл бұрын
very clear!
@milimishra6447
@milimishra6447 7 жыл бұрын
nicely explained........
@anjurawat9274
@anjurawat9274 5 жыл бұрын
well explained!!!
@pushpitgill9545
@pushpitgill9545 4 жыл бұрын
thank you brother
@rajasekharreddy805
@rajasekharreddy805 5 жыл бұрын
can you provide the code for this without using recursive ?
@vaibhavjain9094
@vaibhavjain9094 6 жыл бұрын
sir please make a video on [Print all k-sum paths in a binary tree]
@rajeshd7389
@rajeshd7389 7 жыл бұрын
What is the Time complexity for this ?
@Hiteshkumar-fn8gi
@Hiteshkumar-fn8gi 7 жыл бұрын
Time complexity O(n)... Space complexity O(n) .. where n is total number of nodes in tree source -> www.geeksforgeeks.org/print-a-binary-tree-in-vertical-order-set-3-using-level-order-traversal/
@tarunkr.9041
@tarunkr.9041 5 жыл бұрын
Gave idea now my turn to write code
@sahilmotwani9310
@sahilmotwani9310 4 жыл бұрын
baba tu jhakas hai
@ankitaverma2271
@ankitaverma2271 4 жыл бұрын
thankyousomuch
@Mk-pg5jh
@Mk-pg5jh 7 жыл бұрын
can u upload the graph algorithm ?
@vivekanandkhyade
@vivekanandkhyade 7 жыл бұрын
Yes sure Mohan..!
@familyCart
@familyCart 5 жыл бұрын
Can anybody please tell me what would be the time and space complexity of this algorithm?
@saurabhvemuri5323
@saurabhvemuri5323 5 жыл бұрын
TC:O(N), SC:O(N)
@INSPIRINGNMS
@INSPIRINGNMS 7 жыл бұрын
please upload graph algorithms
@DeepakKumar-wu4dt
@DeepakKumar-wu4dt 4 жыл бұрын
Thankyou sir :-)
@anushaghosh7054
@anushaghosh7054 4 жыл бұрын
It would have been better if you could attach the codes too
@27-Joshna
@27-Joshna Жыл бұрын
Yeah
@vikramlucky92
@vikramlucky92 3 жыл бұрын
Code for leetcode 314. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import collections class Solution: def verticalOrder(self, root: TreeNode) -> List[List[int]]: res = [] if not root: return res seen = {} q = collections.deque() minimum = 0 maximum = 0 q.append([root, 0]) res = [] while q: n = len(q) for i in range(n): node, y_cord = q.popleft() if y_cord in seen: seen[y_cord].append(node.val) else: seen[y_cord] = [node.val] if node.left: q.append([node.left, y_cord - 1]) minimum = min(minimum, y_cord - 1) if node.right: q.append([node.right, y_cord + 1]) maximum = max(maximum, y_cord + 1) for i in range(minimum, maximum + 1): res.append(seen[i]) return res
@kkjjllable
@kkjjllable 6 жыл бұрын
Where can get the sample code?
@rakshith3547
@rakshith3547 4 жыл бұрын
It would have been better if you had provided the code for your algo
@ABHISHEKROY-kd3tw
@ABHISHEKROY-kd3tw 6 жыл бұрын
8:27 literally shook me xD
@dhavaljardosh
@dhavaljardosh 6 жыл бұрын
me as well
@bhupalibaishya2136
@bhupalibaishya2136 6 жыл бұрын
sir, code please !
@rishabsharma5307
@rishabsharma5307 3 жыл бұрын
map mp; void preorder(TreeNode *root, int d) { if(!root) return; mp[d].push_back(root->val); preorder(root->left, d-1); preorder(root->right, d+1); } vector verticalTraversal(TreeNode* root) { mp.clear(); preorder(root, 0); vector vect; for(auto itr = mp.begin(); itr != mp.end(); itr++) { vect.push_back(itr->second); } return vect; }
Level Order Traversal of a Binary Tree (level by level and as a whole)
13:54
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 51 М.
Bottom view of a Binary Tree Algorithm
12:28
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 36 М.
What's in the clown's bag? #clown #angel #bunnypolice
00:19
超人夫妇
Рет қаралды 26 МЛН
Cool Parenting Gadget Against Mosquitos! 🦟👶 #gen
00:21
TheSoul Music Family
Рет қаралды 32 МЛН
She's very CREATIVE💡💦 #camping #survival #bushcraft #outdoors #lifehack
00:26
Spiral (zig-zag) level order traversal of a binary tree
14:12
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 34 М.
Binary Tree Right Side View
8:28
Kevin Naughton Jr.
Рет қаралды 41 М.
Lowest common ancestor of two nodes in Binary Tree Algorithm
13:49
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 57 М.
Vertical order traversal of a binary tree | Leetcode #987
18:03
Diameter of a Binary Tree (Code/ Algorithm)
17:15
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 94 М.
Height of a Binary Tree / Maximum depth of a binary tree Algorithm [REVISITED]
16:50
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 119 М.
Leetcode - Vertical Order Traversal of a Binary Tree (Python)
8:12
Timothy H Chang
Рет қаралды 8 М.
What's in the clown's bag? #clown #angel #bunnypolice
00:19
超人夫妇
Рет қаралды 26 МЛН