Vertical Order Traversal of a Binary tree (Algorithm)

Sdílet
Vložit
  • čas přidán 24. 07. 2024
  • write an algorithm to make vertical order traversal of a binary tree.
    Level order Traversal : • Level Order Traversal ...

Komentáře • 147

  • @prasannachalgeri7152
    @prasannachalgeri7152 Před 6 lety +63

    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 Před 4 lety +11

    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!

  • @abhishekgautam1063
    @abhishekgautam1063 Před 5 lety +2

    Everything is so nicely explained!
    Please continue making videos covering maximum topics and fields.
    Thanks

  • @rainegreen4687
    @rainegreen4687 Před 4 lety +2

    Very clear explanation! This is the first time I watched your video, will surely look for more of these.

  • @deepakpai1893
    @deepakpai1893 Před 4 lety

    I saw a lot of solutions for this question, but yours explained it very well. Thanks.

  • @aiswaryajami2841
    @aiswaryajami2841 Před 3 lety

    Understood the algo in less than 2mins... you are awesome. thank you!!

  • @vivekgr3001
    @vivekgr3001 Před 4 lety

    Thanks for excellent explanation! walking through the algorithm line by line!

  • @Blingblingblingling
    @Blingblingblingling Před 6 lety +3

    video is nicely done. thank you. using any tree traversal should work, filling hash table during traversal. no need for a queue for BFS.

  • @akshaybangar7070
    @akshaybangar7070 Před 6 lety

    ist's best algo video because you solve problems in easy way.Thanks sir

  • @chaitu10552
    @chaitu10552 Před 4 lety

    your explanation covers everything. easy to understand. Thanks

  • @pawandeepchor89
    @pawandeepchor89 Před 5 lety +3

    Awesome, you guys are so cool !!
    Keep going !!

  • @umeshgidnavar8196
    @umeshgidnavar8196 Před 6 lety +1

    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);
    }
    }
    }

  • @pradeepanand5296
    @pradeepanand5296 Před 5 lety +12

    First time watching... Man, u r awesome

  • @travelogue4566
    @travelogue4566 Před 7 lety

    thank so much for nice explanation , great work and keep adding more video .

  • @shreyasmahajan5291
    @shreyasmahajan5291 Před 3 lety

    @Vivekanand Khyade - Algorithm Every Day bhai tuch aapla dada, thank you great explanation!!]

  • @prateektripathi100
    @prateektripathi100 Před 5 lety +1

    This guy is better than many of the useless books available in the market....hats off to you

  • @aanchalsharma5264
    @aanchalsharma5264 Před 4 lety

    U deserves to have lakhs of views
    Keep going and thanks

  • @andreyklysheiko500
    @andreyklysheiko500 Před 5 lety

    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

  • @namrataojha9123
    @namrataojha9123 Před 7 lety

    Nicely explained !!!
    Could you please cover some videos on dynamic programming ?

  • @EternalEntity01
    @EternalEntity01 Před 5 lety

    please upload algorithms for m-way search tree and its different operation. your explanation is very nice.thanking u for this great job

  • @ruchimishra2805
    @ruchimishra2805 Před 7 lety

    very nice explanation.keep them coming

  • @agniswarbakshi7961
    @agniswarbakshi7961 Před 7 lety +9

    nice explanation, thanks for the video..please upload some on dynamic programming too :)

    • @vivekanandkhyade
      @vivekanandkhyade  Před 7 lety +3

      Thanks Agniswar......yes i will upload videos on dynamic programming..!

  • @smayengbam
    @smayengbam Před 5 lety

    Thank you Sir. Well explained. I salute you 👍

  • @parthsoni7370
    @parthsoni7370 Před 2 lety

    Great Explanation! Thanks

  • @sekharbarua839
    @sekharbarua839 Před 3 lety +4

    Vivekanand - How do you remmember all the algo.. It is really nice .. I have followed your video and implement the same using Python..

  • @bhupalibaishya2136
    @bhupalibaishya2136 Před 6 lety

    it's really very nice video and the explanation is so so awesome sir !

  • @shrabanakumar7754
    @shrabanakumar7754 Před 4 lety

    Sir really helpful videos. I have a request, please categorize the videos which will be helpful to go through based on topics .

  • @ivyxue6443
    @ivyxue6443 Před 2 lety

    very good explanation!! Thank you

  • @MYUCOZ1
    @MYUCOZ1 Před 6 lety

    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 Před 5 lety

      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.

  • @TheMihirthakkar
    @TheMihirthakkar Před 3 lety

    Thanks for making this video. It helped me a lot :)

  • @arun26cs
    @arun26cs Před 5 lety

    yes vivek you are super explainatory!!!!!

  • @ayaan_faiz
    @ayaan_faiz Před 6 lety

    Great Explanation. Understood it properly. +1 Subscriber. Thanks

  • @ok123ut
    @ok123ut Před 3 lety

    Amazing explanation!

  • @keyurshah5203
    @keyurshah5203 Před 4 lety

    Nice explaination - easy to implement

  • @saileshverma7353
    @saileshverma7353 Před 3 lety +1

    Awesome explanation bhaya

  • @suchitragiri4546
    @suchitragiri4546 Před 4 lety

    Very nice explained sir!!

  • @successally
    @successally Před 4 lety

    Nicely explained thank you sir🙏

  • @SatishKanaujiyaeb
    @SatishKanaujiyaeb Před 4 lety +1

    Very nice maza aa gya !!!

  • @sachinkulkarni9108
    @sachinkulkarni9108 Před 4 lety +2

    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 Před 3 lety

      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

  • @PrinceKumar-eb8hd
    @PrinceKumar-eb8hd Před 6 lety

    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

  • @argharoy6571
    @argharoy6571 Před 4 lety

    Excellent explanation

  • @TheUmar26
    @TheUmar26 Před 4 lety

    how to get HD of root in while loop so that can add HD for left and right child ??

  • @quangluong5413
    @quangluong5413 Před 4 lety

    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)?

  • @Vj-nu5vx
    @Vj-nu5vx Před 6 lety +2

    please upload algorithms for graph

  • @piyushjha7222
    @piyushjha7222 Před 5 lety +1

    sir how to update hd and its corresponding pair in map??

  • @Shashi0012
    @Shashi0012 Před 4 lety

    Do hashtables allow storing same keys? as you are using hd as the key but multiple nodes have the same hd.

  • @YogeshKumar-px5bd
    @YogeshKumar-px5bd Před 3 lety

    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 Před 2 lety

      Because these are old videos. He stopped uploading regularly and reach went down

  • @785_barneetpanda5
    @785_barneetpanda5 Před 3 lety +2

    If you could add the code along with explanation, it helps a lot

  • @sanaullah-wu4ww
    @sanaullah-wu4ww Před 4 lety

    very helpful. Thank you!

  • @SiddDev
    @SiddDev Před rokem

    hii,thnks for this easy explanation kindly do upload videos on dynamic programming also ....

  • @vinodrammohan
    @vinodrammohan Před 3 lety

    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.

  • @richa6695
    @richa6695 Před 4 lety

    What is the most intuitive answer to this question

  • @amitpadaliya6916
    @amitpadaliya6916 Před 4 lety

    any idea how to put more than one value in hashmap in java

  • @prashantsrivastava9550

    good explanation...thnx

  • @abhishekmulay
    @abhishekmulay Před 6 lety

    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 Před 5 lety

      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

  • @ankitaverma2271
    @ankitaverma2271 Před 4 lety

    This video really helped me..

  • @mdsaif4696
    @mdsaif4696 Před 6 lety +17

    Bhaiya code de do...

  • @arhamzayed8322
    @arhamzayed8322 Před 7 lety

    Vivekanand Khyade, thank you for nice explanation.

  • @mridulmanohar5940
    @mridulmanohar5940 Před 6 lety +2

    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 Před 6 lety +1

      while insertng in the queue, insert with the hd, (object with node and hd for it)

    • @saurabhvemuri5323
      @saurabhvemuri5323 Před 5 lety

      In CPP, You can use queue q; This will store node and its level

  • @milimishra6447
    @milimishra6447 Před 7 lety

    nicely explained........

  • @prashantnagrurkar2784
    @prashantnagrurkar2784 Před 4 lety

    Thank you! Sir.

  • @GauravKawatrakir
    @GauravKawatrakir Před 3 lety

    is it work for "Vertical Order Traversal of a Binary Tree | leetcode 987' ??

  • @harryinsin
    @harryinsin Před 5 lety

    I don't think there is a strict need for level order traversal. A simple recursive inorder traversal would suffice.

  • @INSPIRINGNMS
    @INSPIRINGNMS Před 7 lety

    please upload graph algorithms

  • @vaibhavjain9094
    @vaibhavjain9094 Před 6 lety

    sir please make a video on [Print all k-sum paths in a binary tree]

  • @ashvinsrivastava7378
    @ashvinsrivastava7378 Před 4 lety

    well done sir

  • @tatianazihindula8762
    @tatianazihindula8762 Před 6 lety

    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?

  • @rajasekharreddy805
    @rajasekharreddy805 Před 4 lety

    can you provide the code for this without using recursive ?

  • @anjurawat9274
    @anjurawat9274 Před 5 lety

    well explained!!!

  • @shreeshametkari7963
    @shreeshametkari7963 Před 7 lety +1

    Nice one Sir..

  • @hussainsaifygaming
    @hussainsaifygaming Před 7 lety

    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.

  • @ArpitDhamija
    @ArpitDhamija Před 4 lety +1

    there are difficult codes available on google , please upload a simple code here......

  • @DeepakPandey
    @DeepakPandey Před 7 lety

    Hi @vivekanand thanks for explanatory videos.
    Could you please cover trie data structures and there applications. Thanks in advance !

    • @vivekanandkhyade
      @vivekanandkhyade  Před 7 lety +1

      Thanks Deepak...video on trie data structure is coming soon...!

    • @DeepakPandey
      @DeepakPandey Před 7 lety

      thanks @Vivekanand ... great videos..

  • @veerrajuyeleti8541
    @veerrajuyeleti8541 Před 7 lety

    sir where can we get the code for this

  • @ANJALIGUPTA-vq1cv
    @ANJALIGUPTA-vq1cv Před 2 lety

    u r awesome sir

  • @abhishekjain8869
    @abhishekjain8869 Před 5 lety

    awesome veere

  • @jiangyucara
    @jiangyucara Před 5 lety

    very clear!

  • @effy1219
    @effy1219 Před 7 lety

    very clear drawing

  • @MohsinKhan-sg8wq
    @MohsinKhan-sg8wq Před 5 lety +7

    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 Před 5 lety +1

      In CPP, You can use queue q; This will store node and its level

  • @karansingh-kp3xg
    @karansingh-kp3xg Před 4 lety +2

    Whoever asking code,
    did you ever google "vertical order traversal of binary tree"?

    • @hellostar3063
      @hellostar3063 Před 4 lety

      how to create a hash table

    • @JithendrakumarK
      @JithendrakumarK Před 4 lety

      @@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.

  • @kkjjllable
    @kkjjllable Před 6 lety

    Where can get the sample code?

  • @VivekSingh-vi3cd
    @VivekSingh-vi3cd Před 5 lety +1

    We have to sort by key to get the final result.

    • @Amazi007
      @Amazi007 Před 5 lety

      why not use a TreeMap?

  • @pushpitgill9545
    @pushpitgill9545 Před 4 lety

    thank you brother

  • @nandinichouta4119
    @nandinichouta4119 Před 6 lety

    Can you please let us know what are the time and space complexity

  • @familyCart
    @familyCart Před 5 lety

    Can anybody please tell me what would be the time and space complexity of this algorithm?

  • @tarunkr.9041
    @tarunkr.9041 Před 5 lety

    Gave idea now my turn to write code

  • @zenshyam
    @zenshyam Před 4 lety

    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..

  • @sahilmotwani9310
    @sahilmotwani9310 Před 4 lety

    baba tu jhakas hai

  • @saurabhverma3453
    @saurabhverma3453 Před 4 lety

    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 Před 4 lety

      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 Před 4 lety

      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 Před 4 lety

      @@nikhilm4290 level order traversal using DFS, what does it mean? DFS is for depth search not level. Can u explain it?

    • @saurabhverma3453
      @saurabhverma3453 Před 4 lety

      @@nikhilm4290 yeah thats what I commented that we need to store HD value of nodes.

  • @rajeshd7389
    @rajeshd7389 Před 7 lety

    What is the Time complexity for this ?

    • @Hiteshkumar-fn8gi
      @Hiteshkumar-fn8gi Před 7 lety

      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/

  • @Mk-pg5jh
    @Mk-pg5jh Před 7 lety +1

    can u upload the graph algorithm ?

  • @DeepakKumar-wu4dt
    @DeepakKumar-wu4dt Před 4 lety

    Thankyou sir :-)

  • @ankitaverma2271
    @ankitaverma2271 Před 4 lety

    thankyousomuch

  • @bhupalibaishya2136
    @bhupalibaishya2136 Před 6 lety +1

    sir, code please !

  • @javi2082
    @javi2082 Před 4 lety +2

    Hey, the video is nice. Just a suggestion.
    Please start first with explaining what the question and concept is.

  • @vikramlucky92
    @vikramlucky92 Před 3 lety

    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

  • @SanTosh-zg2iv
    @SanTosh-zg2iv Před 5 lety

    Please find the code here
    github.com/santoshr1016/WeekendMasala/blob/master/itsybitsy/TreeDS/simple_tree.py

  • @rakshith3547
    @rakshith3547 Před 4 lety

    It would have been better if you had provided the code for your algo

  • @rishabsharma5307
    @rishabsharma5307 Před 3 lety

    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;
    }

  • @ArpitDhamija
    @ArpitDhamija Před 5 lety

    pls give the code also !!!!