Vertical Order Traversal of a Binary tree (Algorithm)

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 พ.ย. 2024

ความคิดเห็น • 147

  • @prasannachalgeri7152
    @prasannachalgeri7152 6 ปีที่แล้ว +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 5 ปีที่แล้ว +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!

  • @Blingblingblingling
    @Blingblingblingling 6 ปีที่แล้ว +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.

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

  • @aiswaryajami2841
    @aiswaryajami2841 3 ปีที่แล้ว

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

  • @prateektripathi100
    @prateektripathi100 5 ปีที่แล้ว +1

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

  • @abhishekgautam1063
    @abhishekgautam1063 5 ปีที่แล้ว +2

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

  • @rainegreen4687
    @rainegreen4687 4 ปีที่แล้ว +2

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

  • @umeshgidnavar8196
    @umeshgidnavar8196 7 ปีที่แล้ว +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);
    }
    }
    }

  • @akshaybangar7070
    @akshaybangar7070 6 ปีที่แล้ว

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

  • @shreyasmahajan5291
    @shreyasmahajan5291 3 ปีที่แล้ว

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

  • @deepakpai1893
    @deepakpai1893 4 ปีที่แล้ว

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

  • @sachinkulkarni9108
    @sachinkulkarni9108 4 ปีที่แล้ว +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 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 ปีที่แล้ว +4

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

  • @785_barneetpanda5
    @785_barneetpanda5 4 ปีที่แล้ว +2

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

  • @vivekgr3001
    @vivekgr3001 4 ปีที่แล้ว

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

  • @chaitu10552
    @chaitu10552 5 ปีที่แล้ว

    your explanation covers everything. easy to understand. Thanks

  • @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 6 ปีที่แล้ว

      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.

  • @mdsaif4696
    @mdsaif4696 7 ปีที่แล้ว +17

    Bhaiya code de do...

  • @saileshverma7353
    @saileshverma7353 3 ปีที่แล้ว +1

    Awesome explanation bhaya

  • @ivyxue6443
    @ivyxue6443 3 ปีที่แล้ว

    very good explanation!! Thank you

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

  • @pradeepanand5296
    @pradeepanand5296 5 ปีที่แล้ว +12

    First time watching... Man, u r awesome

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

  • @MohsinKhan-sg8wq
    @MohsinKhan-sg8wq 5 ปีที่แล้ว +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 5 ปีที่แล้ว +1

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

  • @parthsoni7370
    @parthsoni7370 3 ปีที่แล้ว

    Great Explanation! Thanks

  • @argharoy6571
    @argharoy6571 4 ปีที่แล้ว

    Excellent explanation

  • @Vj-nu5vx
    @Vj-nu5vx 6 ปีที่แล้ว +2

    please upload algorithms for graph

  • @agniswarbakshi7961
    @agniswarbakshi7961 7 ปีที่แล้ว +9

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

    • @vivekanandkhyade
      @vivekanandkhyade  7 ปีที่แล้ว +4

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

  • @SatishKanaujiyaeb
    @SatishKanaujiyaeb 4 ปีที่แล้ว +1

    Very nice maza aa gya !!!

  • @pawandeepchor89
    @pawandeepchor89 6 ปีที่แล้ว +3

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

  • @mridulmanohar5940
    @mridulmanohar5940 6 ปีที่แล้ว +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 6 ปีที่แล้ว +1

      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

  • @SiddDev
    @SiddDev ปีที่แล้ว

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

  • @aanchalsharma5264
    @aanchalsharma5264 4 ปีที่แล้ว

    U deserves to have lakhs of views
    Keep going and thanks

  • @suchitragiri4546
    @suchitragiri4546 4 ปีที่แล้ว

    Very nice explained sir!!

  • @VivekSingh-vi3cd
    @VivekSingh-vi3cd 6 ปีที่แล้ว +1

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

    • @Amazi007
      @Amazi007 5 ปีที่แล้ว

      why not use a TreeMap?

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

  • @keyurshah5203
    @keyurshah5203 4 ปีที่แล้ว

    Nice explaination - easy to implement

  • @richa6695
    @richa6695 4 ปีที่แล้ว

    What is the most intuitive answer to this question

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

  • @Shashi0012
    @Shashi0012 4 ปีที่แล้ว

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

  • @ok123ut
    @ok123ut 4 ปีที่แล้ว

    Amazing explanation!

  • @harryinsin
    @harryinsin 5 ปีที่แล้ว

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

  • @javi2082
    @javi2082 4 ปีที่แล้ว +2

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

  • @arun26cs
    @arun26cs 5 ปีที่แล้ว

    yes vivek you are super explainatory!!!!!

  • @successally
    @successally 4 ปีที่แล้ว

    Nicely explained thank you sir🙏

  • @ArpitDhamija
    @ArpitDhamija 4 ปีที่แล้ว +1

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

  • @karansingh-kp3xg
    @karansingh-kp3xg 5 ปีที่แล้ว +2

    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.

  • @ruchimishra2805
    @ruchimishra2805 7 ปีที่แล้ว

    very nice explanation.keep them coming

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

  • @TheMihirthakkar
    @TheMihirthakkar 4 ปีที่แล้ว

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

  • @travelogue4566
    @travelogue4566 7 ปีที่แล้ว

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

  • @namrataojha9123
    @namrataojha9123 7 ปีที่แล้ว

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

  • @ankitaverma2271
    @ankitaverma2271 4 ปีที่แล้ว

    This video really helped me..

  • @piyushjha7222
    @piyushjha7222 5 ปีที่แล้ว +1

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

  • @smayengbam
    @smayengbam 5 ปีที่แล้ว

    Thank you Sir. Well explained. I salute you 👍

  • @shreeshametkari7963
    @shreeshametkari7963 7 ปีที่แล้ว +1

    Nice one Sir..

  • @bhupalibaishya2136
    @bhupalibaishya2136 6 ปีที่แล้ว

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

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

  • @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 6 ปีที่แล้ว

      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

  • @prashantsrivastava9550
    @prashantsrivastava9550 3 ปีที่แล้ว

    good explanation...thnx

  • @arhamzayed8322
    @arhamzayed8322 7 ปีที่แล้ว

    Vivekanand Khyade, thank you for nice explanation.

  • @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 ปีที่แล้ว +1

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

    • @DeepakPandey
      @DeepakPandey 7 ปีที่แล้ว

      thanks @Vivekanand ... great videos..

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

  • @sanaullah-wu4ww
    @sanaullah-wu4ww 4 ปีที่แล้ว

    very helpful. Thank you!

  • @vaibhavjain9094
    @vaibhavjain9094 6 ปีที่แล้ว

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

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

  • @ayaan_faiz
    @ayaan_faiz 7 ปีที่แล้ว

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

  • @effy1219
    @effy1219 7 ปีที่แล้ว

    very clear drawing

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

  • @GauravKawatrakir
    @GauravKawatrakir 3 ปีที่แล้ว

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

  • @amitpadaliya6916
    @amitpadaliya6916 5 ปีที่แล้ว

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

  • @ANJALIGUPTA-vq1cv
    @ANJALIGUPTA-vq1cv 2 ปีที่แล้ว

    u r awesome sir

  • @TheUmar26
    @TheUmar26 4 ปีที่แล้ว

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

  • @INSPIRINGNMS
    @INSPIRINGNMS 7 ปีที่แล้ว

    please upload graph algorithms

  • @ashvinsrivastava7378
    @ashvinsrivastava7378 4 ปีที่แล้ว

    well done sir

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

  • @tatianazihindula8762
    @tatianazihindula8762 7 ปีที่แล้ว

    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

  • @tarunkr.9041
    @tarunkr.9041 5 ปีที่แล้ว

    Gave idea now my turn to write code

  • @anushaghosh7054
    @anushaghosh7054 4 ปีที่แล้ว

    It would have been better if you could attach the codes too

  • @nandinichouta4119
    @nandinichouta4119 6 ปีที่แล้ว

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

  • @prashantnagrurkar2784
    @prashantnagrurkar2784 5 ปีที่แล้ว

    Thank you! Sir.

  • @abhishekjain8869
    @abhishekjain8869 5 ปีที่แล้ว

    awesome veere

  • @jiangyucara
    @jiangyucara 5 ปีที่แล้ว

    very clear!

  • @milimishra6447
    @milimishra6447 7 ปีที่แล้ว

    nicely explained........

  • @pushpitgill9545
    @pushpitgill9545 4 ปีที่แล้ว

    thank you brother

  • @ayushthakur733
    @ayushthakur733 4 ปีที่แล้ว +1

    Telephone rings at 8:35 😂😂😂😂

  • @anjurawat9274
    @anjurawat9274 5 ปีที่แล้ว

    well explained!!!

  • @familyCart
    @familyCart 5 ปีที่แล้ว

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

  • @Mk-pg5jh
    @Mk-pg5jh 7 ปีที่แล้ว +1

    can u upload the graph algorithm ?

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

  • @rakshith3547
    @rakshith3547 4 ปีที่แล้ว

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

  • @sahilmotwani9310
    @sahilmotwani9310 4 ปีที่แล้ว

    baba tu jhakas hai

  • @bhupalibaishya2136
    @bhupalibaishya2136 6 ปีที่แล้ว +1

    sir, code please !

  • @DeepakKumar-wu4dt
    @DeepakKumar-wu4dt 4 ปีที่แล้ว

    Thankyou sir :-)

  • @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/

  • @ankitaverma2271
    @ankitaverma2271 4 ปีที่แล้ว

    thankyousomuch

  • @kkjjllable
    @kkjjllable 6 ปีที่แล้ว

    Where can get the sample code?

  • @ABHISHEKROY-kd3tw
    @ABHISHEKROY-kd3tw 6 ปีที่แล้ว +1

    8:27 literally shook me xD

  • @veerrajuyeleti8541
    @veerrajuyeleti8541 7 ปีที่แล้ว

    sir where can we get the code for this