L23. Bottom View of Binary Tree | C++ | Java

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

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

  • @takeUforward
    @takeUforward  3 ปีที่แล้ว +54

    Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79

  • @bharathkumar5870
    @bharathkumar5870 3 ปีที่แล้ว +22

    // code for recrsive approach,just keep track of row number.
    //Structur of map: colum_no={data,rownumber}
    //if row number is larger than previous stored data,then replace.
    void f(BinaryTreeNode * root, int row,int col,map &mp){
    if(root==0)return;
    if(row>=mp[col].second)
    mp[col]={root->data,row};
    f(root->left,row+1,col-1,mp);
    f(root->right,row+1,col+1,mp);
    }

  • @adityabalodi1185
    @adityabalodi1185 2 ปีที่แล้ว +66

    In case the question asks to store the left value instead of right when both nodes are at same place, just do the level order traversal from right to left.

    • @Ramu9119
      @Ramu9119 10 หลายเดือนก่อน +2

      Genius

  • @RitiKumari
    @RitiKumari 3 ปีที่แล้ว +100

    I am very much happy and impressed by the fact at last you let us know why one shouldn't use recursion . Awesome explaination Must Say !!!

    • @soumyamondal
      @soumyamondal 2 ปีที่แล้ว +7

      Oh lol, I saw your interview today.

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

      @@soumyamondal Heyaa , small world :P

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

      you are popular on linkedin right?

    • @theexplorer9012
      @theexplorer9012 5 หลายเดือนก่อน +4

      lol i did it with recursion. also top view . its not like that we cant do it ,

    • @mohit7717
      @mohit7717 5 หลายเดือนก่อน +1

      You also learn from striver DSA playlist?

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

    Understood.
    Recursive code:
    Modification: keep track of ht along with line and check if there is a element present on the line or not. If not then insert that, otherwise check if ht is greater than or equal to the previous or not. We have to include == becasue we will always traverse the left part first and then second so if in the right subtree there is a node at the same level then that will be the rightest one.
    void inorder(BinaryTreeNode* root, int x, int y, map &bottomView) {
    if(root == NULL) return;
    if(bottomView.find(x) == bottomView.end() ||
    y >= bottomView[x].first) {
    bottomView[x].first = y;
    bottomView[x].second = root -> data;
    }
    inorder(root -> left, x - 1, y + 1, bottomView);
    inorder(root -> right, x + 1, y + 1, bottomView);
    }
    vector bottomView(BinaryTreeNode * root){
    vector res;
    if(root == NULL) return res;
    // x y data
    map bottomView;
    inorder(root, 0, 0, bottomView);
    for(auto p: bottomView) {
    res.push_back(p.second.second);
    }
    return res;
    }

  • @VishalGupta-xw2rp
    @VishalGupta-xw2rp 2 ปีที่แล้ว +17

    TC will be O(N) for BFS Traversal * O(LogN) as we are using Map.
    So overall O(N*LogN)
    Yeah for space complexity you can say overall it will be O(N)

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

      Yeas

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

      can you please tell how T(c) will be O(N log n) , because in video he has mentioned T(c) to be O(N) .

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

      @@itskaaryan7 because we are using a map

    • @iitgupta2010
      @iitgupta2010 2 หลายเดือนก่อน +1

      @@Dontpushyour_luck this can be simply avoid by finding the leftmost and rightmost column length.

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

    done before you explaining... that's the level of ur teaching... u make us think nd do it ourselves.... Thanks a lot #saviour

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

    Thanks Striver Bhaiya for Uploading such high quality content for free on TH-cam it feels more than any paid content.

  • @abhishek_0513
    @abhishek_0513 2 หลายเดือนก่อน

    This explanation is astounding! The explanation of why recursive traversal is ineffective in this situation struck a deep chord.

  • @charlesbabbage6786
    @charlesbabbage6786 7 หลายเดือนก่อน +1

    Truly AMAZING explanation. You're such a KING!

  • @ammanchhetri6716
    @ammanchhetri6716 5 หลายเดือนก่อน +1

    the change we can do is ig...we can carry another parameter as depth...and we will create a map like map ...where the int inside the pair is the depth...so we only update the vertical if the current depth is greater than the stored depth....maybe this should work

    • @avengergirl_0464
      @avengergirl_0464 4 วันที่ผ่านมา +1

      It has to work but I tried it and I can't implement it myself

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

    Best DSA content. Miles and leagues ahead of other channels! 🙌🙌🙌

  • @lakshmand8413
    @lakshmand8413 3 หลายเดือนก่อน +2

    In top view of the tree we check before adding to the map if there is an existing node from that particular line number , simply remove that checking condition that's all your code for bottom view is done :)

  • @AdityaMaurya-dw3od
    @AdityaMaurya-dw3od 2 หลายเดือนก่อน

    Being able to solve these question on my own coz of your previous explanations. Thankyou Striver!!!

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

    dhanybad bhaiya aapke wajah se hum ab tree pe chadna start kar diya hai thoda thoda

  • @algoman6589
    @algoman6589 2 ปีที่แล้ว +1

    I was just doing by recursion without thinking of the last example which u have shown ..thank you so much ❤️

  • @aniketsaxena6691
    @aniketsaxena6691 2 ปีที่แล้ว +3

    As soon as you said vertical order traversal, I closed the tab and solved the question. And I got to learn about vertical order traversal, 🤣

  • @ayushgautam8000
    @ayushgautam8000 2 หลายเดือนก่อน +1

    Great explanation sir. Masterpiece !

  • @mrudul5018
    @mrudul5018 2 ปีที่แล้ว

    Thanx bhaiya mujhe bottom view samjne me dikkat jari thi. Ye video me first attempt me samaj gaya.

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

    Completed 24/54(44% done) !!!

  • @iamnottech8918
    @iamnottech8918 4 หลายเดือนก่อน

    I solved this question on my own after doing last q on finding top view , just came here to see what better can be done .

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

    Using recursion can also be solved
    void preorder(Node *root, int vlevel, int hlevel, map &m)
    {
    if (root == 0)
    return;
    if (m.find(vlevel) == m.end() || m[vlevel].first data};
    preorder(root->left, vlevel - 1, hlevel + 1, m);
    preorder(root->right, vlevel + 1, hlevel + 1, m);
    }
    vector bottomView(Node *root)
    {
    map m;
    preorder(root, 0, 0, m);
    vector res;
    for (auto ele : m)
    {
    res.push_back(ele.second.second);
    }
    return res;
    }

  • @ritikshandilya7075
    @ritikshandilya7075 5 หลายเดือนก่อน

    Thanks @striver for amazing content

  • @satyamsingh_47
    @satyamsingh_47 3 ปีที่แล้ว +10

    Shouldn't the worst case time complexity be O(n Logn) in case of skewed tree, because of map/TreeMap?

    • @takeUforward
      @takeUforward  3 ปีที่แล้ว +8

      Yeah i have left the tree map complexity to be added by the user

  • @TheWierdVibe
    @TheWierdVibe 2 ปีที่แล้ว

    The best coding channel on TH-cam!

  • @prabhakaran5542
    @prabhakaran5542 2 หลายเดือนก่อน +1

    Understood ❤

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

    very easy to undertsnad the logic after watching previous top view video,thanks a lott

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

    Thank You So Much for this wonderful video........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @amanasrani6405
    @amanasrani6405 11 วันที่ผ่านมา

    Understtooooooooooddd
    THansk You Bhaiya

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

    i was confused about depth traversal , now it is clear

  • @Ramu9119
    @Ramu9119 10 หลายเดือนก่อน

    Awesome Lecture

  • @culeforever5408
    @culeforever5408 9 หลายเดือนก่อน +1

    understood 😇

  • @Sanjaysharma-sd3wn
    @Sanjaysharma-sd3wn 3 ปีที่แล้ว +2

    explained very well, sirf apke video se bfs theek se samaj paya.
    also had a doubt, why cant we use recursion(postorder traversal) with map? once we map for each horizontal distance, we can ignore other nodes, during traversal.

    • @vaibhavchhabra800
      @vaibhavchhabra800 2 ปีที่แล้ว

      Same questipn , why complicate things , no need to use level order traversal

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

    if we use unordered_map and keep track of leftmost element we can actually keep the complexity to minimum . map has push and find complexity of log(N).....even though we are not pushing each element but we are checking whether to push or not for each element .

  • @DeadPoolx1712
    @DeadPoolx1712 19 วันที่ผ่านมา

    UNDERSTOOD;

  • @apmotivationakashparmar722
    @apmotivationakashparmar722 23 วันที่ผ่านมา

    Thank you so much.

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

    THANK YOU SO MUCH , YOUR EXPLANATION WAS VERY MUCH UNDERSTANDABLE

  • @per.seus._
    @per.seus._ ปีที่แล้ว

    UNDERSTOOD

  • @abhishektiwari8431
    @abhishektiwari8431 2 ปีที่แล้ว

    Best DSA content, top notch

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

    Recursive wala part was excellent 🔥🔥🔥👌👌👌

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

      // code for recrsive approach,just keep track of row number.
      //Structur of map: colum_no={data,rownumber}
      //if row number is larger than previous stored data,then replace.
      void f(BinaryTreeNode * root, int row,int col,map &mp){
      if(root==0)return;
      if(row>=mp[col].second)
      mp[col]={root->data,row};
      f(root->left,row+1,col-1,mp);
      f(root->right,row+1,col+1,mp);
      }

  • @KartikeyTT
    @KartikeyTT 3 หลายเดือนก่อน

    tysm sir

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

    Very well explained sir

  • @cinime
    @cinime 2 ปีที่แล้ว

    Understood! So wonderful explanation as always, thank you very much!!

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

    class Solution:
    def __init__(self):
    self.values={}
    def solve(self,root,x,level):
    if root is None :
    return
    if x not in self.values.keys() or self.values[x][1]

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

      for sorting the keys it will take nlogn right!!!!!

  • @hardikjain-brb
    @hardikjain-brb 5 หลายเดือนก่อน

    bfs dfs both work smooth !

  • @shreyaagarwal4320
    @shreyaagarwal4320 5 หลายเดือนก่อน

    The time complexity should be O(nlogn) right ?
    bcs of sorted function used in python.
    pls some correct me if i am wrong

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

    Very high Quality content !

  • @MdSarfrazcs
    @MdSarfrazcs 2 ปีที่แล้ว

    I have solve the question via both level order as well as DFS still I am excited to see striver solution

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

    Understood very well .Thank you bhaiya amazing trees playlist keep doing this bhaiya :)

  • @codeman3828
    @codeman3828 7 หลายเดือนก่อน

    Undertsood

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

    Thank you sir

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

    Recursive soln: [JAVA]
    class Pair {
    int level;
    int nodeVal;
    Pair (int level, int nodeVal) {
    this.level = level;
    this.nodeVal = nodeVal;
    }
    }
    public class Solution {
    public static List bottomView(TreeNode root) {
    // Write your code here.
    TreeMap map = new TreeMap();
    travel(0, 0, root, map);
    List ans = new ArrayList();
    for (Pair pair: map.values())
    ans.add(pair.nodeVal);
    return ans;
    }
    static void travel(int x, int y, TreeNode cur, TreeMap map) {
    if (cur == null) return;
    if (!map.containsKey(x))
    map.put(x, new Pair(y, cur.val));
    else if(map.get(x).level

  • @ashishpradhan6250
    @ashishpradhan6250 3 หลายเดือนก่อน

    understood bro

  • @tgayush1424
    @tgayush1424 5 หลายเดือนก่อน

    it can be solved in O(n) also , you didn't covered that?

  • @rishabhdwivedi5217
    @rishabhdwivedi5217 2 ปีที่แล้ว

    wow nice approach 😀😀

  • @ayushgaurabh8604
    @ayushgaurabh8604 10 หลายเดือนก่อน

    understood

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

    You have used map and map sort the Data then How Time Complexity is O(N) ??
    Why not O(Nlogn) ??

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

      Basically in java its o(1), hence i have written, you can use n log n if using c++ and not unordered map

    • @mutthikarunakar8951
      @mutthikarunakar8951 3 ปีที่แล้ว +2

      @@takeUforward But u have used treeMap which has time complexity of O(logn) in worst case while inserting elements so the time complexity will O(nlogn)

  • @akash-tj8ru
    @akash-tj8ru 2 ปีที่แล้ว

    11:44 we need right one only in BV of BT...so recursive approach would work here...right?

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

    thanks sir , great efforts

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

    Understood,able to solve by myself

  • @brb4r333
    @brb4r333 4 หลายเดือนก่อน

    or we could just do top view but remove the if statement which checks if the line already is there in the map, as we are essentially trying to put the latest value for a particular vertical line

  • @ravneetsingh1922
    @ravneetsingh1922 2 ปีที่แล้ว

    thanks ,u r doing great job

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

    Understood . Great series

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

    Striver is just awesome

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

    Thanks! Understood!

  • @nagavedareddy5891
    @nagavedareddy5891 2 ปีที่แล้ว

    Huge respect...❤👏

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

    nice explanation, clean code

  • @shailshah9021
    @shailshah9021 2 ปีที่แล้ว

    The solution may be incorrect for the following tree:
    root = Node(0)
    root.left = Node(1)
    root.right = Node(2)
    root.left.right = Node(3)
    root.right.left = Node(4)
    Actual output: 1 4 5
    Expected Output: 1 3 4 5
    Output is incorrect because the distance of {node, node.left.right, node.right.left} for any node is the same. So, both node.left.right and node.right.left should be added to the output, instead of just selecting node.right.left.

    • @kartikeyvashisht9182
      @kartikeyvashisht9182 2 ปีที่แล้ว

      There is no node with value (5) inserted into the tree according to the tree provided, and according to the tree the output should be 1 4 2. Yes vertical of {root, root->left->right, root->right->left} is same, but the value of {root->right->left} would be selected as it hides the 2 nodes {root, root->left->right} above it. Hope it helps!

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

    Explained well, good job buddy... keep doing videos✨

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

    completed lecture 23 of free ka tree series.

  • @yashkhatwani3198
    @yashkhatwani3198 2 ปีที่แล้ว

    Thank you bhaiya

  • @umangbehl8152
    @umangbehl8152 2 ปีที่แล้ว

    thank you striver

  • @chetangupta5390
    @chetangupta5390 2 ปีที่แล้ว

    in line 14---Node*node=it.first
    then why we are doing ans.push_back(it.second)???

  • @VarunSharma-xd8xd
    @VarunSharma-xd8xd 5 หลายเดือนก่อน

    how does it ensure that the values stored in the hashmap at last are sorted.I had to apply a seperate function for sorting according to hd

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

    thank you so much bhaiyaa

  • @ajayypalsingh
    @ajayypalsingh 2 ปีที่แล้ว

    💚

  • @arnab4151
    @arnab4151 2 ปีที่แล้ว

    In case anyone needs help:
    // Problem link: practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1
    // Approach 1: Recursive Approach:
    class Solution {
    public:
    void bottomViewUtil(Node *root, int distance, int height, map &mp){
    if(root == NULL)
    return;
    if(mp.find(distance) == mp.end())
    mp[distance] = {height, root->data};
    else{
    if(mp[distance].first data};
    }
    bottomViewUtil(root->left, distance - 1, height + 1, mp);
    bottomViewUtil(root->right, distance + 1, height + 1, mp);
    }
    vector bottomView(Node *root){
    map mp; // {distance, {level, ans}}
    int distance = 0; // How farther away towards left/right from the root
    int height = 1;
    bottomViewUtil(root, distance, height, mp);

    vector ans;
    for(auto it : mp)
    ans.push_back(it.second.second);
    return ans;
    }
    };
    // Approach 2: Iterative Approach:
    class Solution {
    public:
    vector bottomView(Node *root){
    if(root == NULL)
    return {};
    map mp; // {distance, ans}
    queue q; // {node, distance}
    q.push({root, 0});

    while(!q.empty()){
    int sz = (int)q.size();
    for(int i = 0; i < sz; i++){
    auto cur = q.front();
    q.pop();
    mp[cur.second] = cur.first->data;
    if(cur.first->left != NULL)
    q.push({cur.first->left, cur.second - 1});
    if(cur.first->right != NULL)
    q.push({cur.first->right, cur.second + 1});
    }
    }

    vector ans;
    for(auto it : mp)
    ans.push_back(it.second);
    return ans;
    }
    };
    // Time Complexity: O(n)
    // Space Complexity: O(n)

  • @harshdeepak3281
    @harshdeepak3281 2 ปีที่แล้ว

    in love with your content!!!

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

    UNDERSTOOD

  • @lavanyaprakashjampana933
    @lavanyaprakashjampana933 2 ปีที่แล้ว

    we love your content and we love you ....🖤

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

    Great Bhaiya 🙏🙏

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

    public List bottomView(Node root)
    {
    TreeMap map = new TreeMap();
    Queue q = new LinkedList();
    q.add(new Pair(root, 0));
    while(!q.isEmpty())
    {
    Pair p = q.poll();
    Node node = p.node;
    int x = p.num;
    if(!map.containsKey(x))
    map.put(x, node.data);
    else
    map.put(x, node.data);
    if(node.left!=null)
    q.add(new Pair(node.left, x-1));

    if(node.right!=null)
    q.add(new Pair(node.right, x+1));

    }
    List list = new ArrayList();
    for(int val : map.values())
    list.add(val);
    return list;
    }
    WORKS 👍

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

    Tq sir

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

    VIDEO aagya 🙌✌️

  • @sanketatmaram
    @sanketatmaram 2 ปีที่แล้ว

    understood

  • @altamashsabri8142
    @altamashsabri8142 2 ปีที่แล้ว

    Understood

  • @krishnavamsichinnapareddy
    @krishnavamsichinnapareddy 2 ปีที่แล้ว

    Understood 👍

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

    sir,
    Moj kar de

  • @RJ-bd3ww
    @RJ-bd3ww 2 ปีที่แล้ว

    But hash maps in Java are not sorted they put the values in random in if we want to sort it we need to use a comparator and which will again add up time complexity

    • @0xDhaval
      @0xDhaval 2 ปีที่แล้ว

      use treemap

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

    solved without watching the vidd

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

    Understood!

  • @exploremore877
    @exploremore877 2 ปีที่แล้ว

    Can we do it in O(n) time and O(n) space ??

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

    ❤❤❤❤❤❤❤

  • @ashwinraghunath4453
    @ashwinraghunath4453 2 ปีที่แล้ว

    Dont we need to sort the map here in java?

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

    2:20 -3:55

  • @your_name96
    @your_name96 2 ปีที่แล้ว +3

    My dfs version :
    void hlp(Node*root,int hd,int lvl, map&mp){
    if(!root)return ;
    if(!mp.count(hd) or lvl >= mp[hd].first){ // = is very important as it prints the later node if they have the same coordinated
    mp[hd] = {lvl,root->data};
    }
    hlp(root->left,hd-1,lvl+1,mp);
    hlp(root->right,hd+1,lvl+1,mp);
    }
    vector bottomView(Node *root) {
    // Your Code Here
    if(!root)return {};
    vectorans;
    mapmp;
    if(!root->left and !root->right)return {root->data};
    hlp(root,0,0,mp);
    for(auto &el : mp){
    ans.push_back(el.second.second);
    }
    return ans;
    }
    Time : O(nlogn)
    Space : O(n)

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

    But in map duplicate key not allowed ,so how the value overwrite in this program

    • @dannapurnad3930
      @dannapurnad3930 7 หลายเดือนก่อน

      did you got it . why ?

  • @utkarshsharma6650
    @utkarshsharma6650 2 ปีที่แล้ว

    understooood. thanks :)

  • @ankitkumaryadav562
    @ankitkumaryadav562 2 ปีที่แล้ว

    Instead of bfs, I try to implement using dfs but it gives me the wrong answer
    map m;
    void dfs(Node* root, int cnt)
    {
    if (root == NULL)
    return ;
    m[cnt] = root->data;
    dfs(root->left, cnt-1);
    dfs(root->right,cnt+1);
    }
    vector bottomView(Node *root)
    {
    m.clear();
    dfs(root,0);
    vector v;
    for (auto x : m)
    v.push_back(x.second);
    return v;
    }

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

    aagya aagyaa...