L24. Right/Left View of Binary Tree | C++ | Java

Sdílet
Vložit
  • čas přidán 28. 08. 2021
  • Entire DSA Course: takeuforward.org/strivers-a2z...
    Check our Website:
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    #treeSeries #striver #placements

Komentáře • 276

  • @takeUforward
    @takeUforward  Před 2 lety +84

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

  • @uRamPlus
    @uRamPlus Před 2 lety +62

    self notes:
    🚀 for every level, the first node (on the right side) will be our right side view
    🚀 if the level of the tree == my vector's size, I need to push it into my vector
    🚀 if at any point we reach a null node, we just need to return (base case)

    • @moksh455
      @moksh455 Před 4 měsíci

      That code is self explanatory no need to maintain notes

    • @ritwikdurga3855
      @ritwikdurga3855 Před měsícem +1

      @@moksh455go touch grass

  • @anmolswarnkar7707
    @anmolswarnkar7707 Před 2 lety +98

    Amazing explanation! I like the fact that you go step by step (like a compiler would) over the example. Keep posting these videos!

  • @rohan8758
    @rohan8758 Před 10 měsíci +24

    For Left Side View , call the recursive function with the left node and then with the right node .
    f(node->left, level+1);
    f(node->right, level+1);

  • @kuldeepkushwah565
    @kuldeepkushwah565 Před 2 lety +53

    Thank you striver for all your effort, your content is worth more than any paid courses.
    This Chanel is full of treasure.

    • @sarathchandra941
      @sarathchandra941 Před 2 lety +1

      Hiidden behind the youtube recommendation algo..🥺
      #open sesame😎 -- tree ka free series treasure will be urs🤭

  • @VishalGupta-xw2rp
    @VishalGupta-xw2rp Před rokem +18

    What i came up was that (before watching video)
    For(Right View)
    Use Vertical order only
    This time instead of left - 1, we will increase both and Mark each node *levels* not their *vertical* left + 1, right + 1
    Now simply as we go we will store the latest level by m[level] = node->data.
    Because of map property, it will itself ensure that all the latest one will be there so overwrites the previous
    But what a technique and Amazing approach.... Man when will i begin to think like that ♥️🔥

    • @priyankarkoley
      @priyankarkoley Před 3 měsíci

      I believe that will end up with nlog(n) time complexity.

  • @krishnasudan3410
    @krishnasudan3410 Před 2 lety +27

    My iterative approach.. thanks Bhaiya for everything.. Such a gem in coding community
    vector rightView(Node *root){
    vector res;
    if(root==NULL) return res;
    queue q;
    q.push(root);
    while(!q.empty()){
    Node *temp = q.front();
    res.push_back(temp->data);
    int size = q.size();
    for(int i=0;iright!=NULL) q.push(curr->right);
    if(curr->left!=NULL) q.push(curr->left);
    }
    }
    return res;
    }

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

      In your code, you should push left node before the right node in the queue in for loop

    • @isheep9025
      @isheep9025 Před rokem +3

      @@gautamjh no its correct for right view

    • @rutwikmore7462
      @rutwikmore7462 Před rokem

      bro I also wrote the exact same code..😄😄

  • @blitzkrieg5454
    @blitzkrieg5454 Před 2 lety +17

    I feel so lucky to have a teacher like you, thanks a lottt!!!

  • @shubh13799
    @shubh13799 Před 2 lety +14

    your explanation techniques are phenomenal, clear concepts and concise code. Loving the way you code.

  • @Dontpushyour_luck
    @Dontpushyour_luck Před 9 měsíci +3

    so clever technique of using recursion and size of data structure to check if it is the first node that we came to in this level. no wonder you are candidate master on codeforces!

  • @ssaha7714
    @ssaha7714 Před 2 lety +1

    Too good. Amazed to see the explanation… clear and to the point..

  • @rishabhinc2936
    @rishabhinc2936 Před 7 měsíci

    i could have never ever thought of comparing level and ds size.striver ur insane man

  • @cinime
    @cinime Před rokem +2

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

  • @falgunitagadkar4097
    @falgunitagadkar4097 Před rokem +2

    Your approach to solve problems is just commendable👏👏
    Thanks for providing so valuable content for free!
    Again...the same thing...Hats off to you Striver ✌

  • @sujan_kumar_mitra
    @sujan_kumar_mitra Před 2 lety

    Understood! Nice intuition to figure out if we are visiting the depth first or not

  • @4mulate
    @4mulate Před 26 dny +1

    My iterative approach which was before I watched your explanation:
    //just push to ans vector when we are at last node in the queue.
    class Solution {
    public:
    vector rightSideView(TreeNode* root) {
    vector ans;
    if(root==nullptr) return {};
    queue q;
    q.push(root);
    while(!q.empty()){
    int size = q.size();
    for(int i=0;ival);
    }
    q.pop();
    if(front->left!=nullptr) q.push(front->left);
    if(front->right!=nullptr) q.push(front->right);
    }
    }
    return ans;
    }
    };

  • @avinashgupta2308
    @avinashgupta2308 Před 2 lety +2

    Amazing approach! and definitely the way you teach is just ❤

  • @BTEEELavkushYadav
    @BTEEELavkushYadav Před 2 lety +1

    Millions of thanks to you bro
    you make my concept crystal clear
    I have subscribed ur channel instant

  • @ArushiRoy2823
    @ArushiRoy2823 Před 3 měsíci +1

    Oaw , what an amazing explanation and logic behind the code is superb 🥺

  • @sourabh258
    @sourabh258 Před 2 lety +1

    Excellent stuff, thanks for such a simple explanation!

  • @prajaktakapoor7520
    @prajaktakapoor7520 Před 6 měsíci

    Great solution sir!! Really impressed

  • @U-DAY
    @U-DAY Před 2 lety

    bro i never saw this much like amazing explanation ..... superb awesome u are....
    loving ur teaching bro........................

  • @samarthsingh2705
    @samarthsingh2705 Před rokem +2

    I first watched the video of apna college youtube channel where they discussed the iterative method using level order traversal. This code here in this video is very short and also very well explained by striver. Thanks TUF for such amazing content.

  • @stormshadow76
    @stormshadow76 Před rokem

    This is the most brilliant solution !!!!!!! Amazing !!!

  • @animeshbarole
    @animeshbarole Před rokem +2

    if(level==ds.size()) ans.push_back(node->val) is just Mind blowing technique ....... Take a bow Striver .

  • @SohamDutta222
    @SohamDutta222 Před měsícem

    Man, You are the best.. best explanation

  • @user-xy5ln4zh5w
    @user-xy5ln4zh5w Před 5 měsíci

    The way how you use recursion is damn good

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

    Easy solution for left view level order traversal:
    #include
    using namespace std;
    vector getLeftView(TreeNode *root)
    {
    if (root == NULL)
    return {};
    vector ans;
    queue q;
    q.push(root);
    while (!q.empty())
    {
    int sz = q.size();
    for (int i = 0; i < sz; i++)
    {
    auto front = q.front();
    q.pop();
    if (i == 0)
    ans.push_back(front->data);
    if (front->left)
    q.push(front->left);
    if (front->right)
    q.push(front->right);
    }
    }
    return ans;
    }

  • @sachinvarma9949
    @sachinvarma9949 Před 20 dny

    that was a mind blown solution

  • @sifatsamir0076
    @sifatsamir0076 Před 27 dny

    nice explaination ❤ Love from Bangladesh❤

  • @prasadprashantb.4001
    @prasadprashantb.4001 Před 8 měsíci

    You are amazing bro❤ keep it up🙌

  • @stark3585
    @stark3585 Před 2 lety

    Vey good concept of vertical lines. Keep going bro....

  • @Prateek03
    @Prateek03 Před 2 lety +2

    Thank you striver, you made things easy for us 🔥

  • @adebisisheriff159
    @adebisisheriff159 Před 5 měsíci

    Thanks so much Striver !!!!!

  • @bhashkarbelwal4116
    @bhashkarbelwal4116 Před 4 měsíci

    wow thanks a lot for the explanation
    '

  • @uRamPlus
    @uRamPlus Před 2 lety

    thank you for the dry run explanation!! amazing

  • @HimanshuSingh-hd8of
    @HimanshuSingh-hd8of Před 2 lety

    //Implemetation of above approach
    Initially we pass 0 in level res is data structure that we are using for storing the elements
    void find_right_view(Node *root,vector&res,int level){
    if(root==NULL){return ;}
    if(level==res.size()){
    res.push_back(root->data);
    }
    find_right_view(root->right,res,level+1);
    find_right_view(root->left,res,level+1);
    }

    • @ojasthengadi9681
      @ojasthengadi9681 Před 2 lety

      hey can you please explain why the level becomes 0 once we reach to root node before travsersing to left

  • @akhilakapse204
    @akhilakapse204 Před 2 lety +2

    Please keep at it bro. These videos are super helpful!

  • @Sujit13484
    @Sujit13484 Před 2 lety +3

    Good work. I like the way you explain each problem.
    Once change we can do. I think we can do it without using Stack also by keeping a counter for max level reached from right tree. Here is code below.
    class Solution {
    int maxLevelSoFar = -1;
    public List rightSideView(TreeNode root) {
    List result = new ArrayList();
    rightRecursive(root, 0, result);
    return result;
    }
    private void rightRecursive(TreeNode root, int level, List result) {
    if(root == null) {
    return;
    }
    if(level > maxLevelSoFar) {
    result.add(root.val);
    }
    rightRecursive(root.right, level + 1, result);
    rightRecursive(root.left, level + 1, result);
    maxLevelSoFar = Math.max(maxLevelSoFar, level);
    }
    }

  • @areebahmadsiddiqui2648
    @areebahmadsiddiqui2648 Před 2 lety +2

    I am watching your channel the very first time and maaaaan you are damn good thanq for this

  • @sharda16april
    @sharda16april Před 2 lety

    Amazing Striver.. Such an amazing explanation. I used BFS and it was not as clean as your code.

  • @Kaushik846
    @Kaushik846 Před rokem

    Awesome technique and explanation!!!

  • @aakashsingh5076
    @aakashsingh5076 Před rokem

    Amazing Explaintaion 👏❤️
    Keep Posting These kinds of Content 🙏👍

  • @sakshiaggarwal3838
    @sakshiaggarwal3838 Před 2 lety

    Very well explained 👍

  • @ishangujarathi10
    @ishangujarathi10 Před rokem +1

    awesome logic of level==ds.size(), unserstood in depth !!!

  • @per.seus._
    @per.seus._ Před 8 měsíci +1

    UNDERSTOOD

  • @Shivi32590
    @Shivi32590 Před 15 dny

    thank you

  • @maradanikhil6882
    @maradanikhil6882 Před rokem +1

    Here is the level order traversal for right side view:
    class Solution {
    public:
    vector rightSideView(TreeNode* root) {
    queueq;
    q.push(root);
    vectorans;
    if(root==NULL)
    return ans;
    while(!q.empty()){
    int size=q.size();
    int a=0;
    for(int i=0;ival;
    if(node->left) q.push(node->left);
    if(node->right) q.push(node->right);
    }
    ans.push_back(a);
    }return ans;
    }
    };

  • @damandeepsingh6037
    @damandeepsingh6037 Před 2 lety

    Amazing explanation!

  • @sharmanihal99
    @sharmanihal99 Před měsícem

    This DFS Solution was more intutive for me.
    class Solution:
    def __init__(self):
    self.rightmost_values = defaultdict(int)
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
    if not root:
    return []
    self.reversePreorder(root, 0)
    return self.rightmost_values.values()
    def reversePreorder(self, root, level):
    if not root: return
    if level not in self.rightmost_values:
    self.rightmost_values[level] = root.val
    # Traverse right subtree first for getting rightmost values
    self.reversePreorder(root.right, level + 1)
    self.reversePreorder(root.left, level + 1)

  • @nitunsingh6986
    @nitunsingh6986 Před 2 lety

    We can use set data structure over here to store right view only same for left view.

  • @guru579
    @guru579 Před 2 lety +1

    Amazing Explanation 🔥🔥

  • @vishalsrivastava3137
    @vishalsrivastava3137 Před 2 lety

    Amazing video! 👏🏻🙌🏻

  • @js__talks
    @js__talks Před 6 měsíci

    Which tool you are using to write and sketch here?

  • @krishnavamsichinnapareddy

    Simple nailed it 👏

  • @rohandevaki4349
    @rohandevaki4349 Před 2 lety +3

    very simple approach and great explaination, how do you get these approaches? i wasnt able to get any approach even after trying so much.

  • @vishalkumarchauhan5101

    Amazing explanation! love u bro.. keep posting like that

  • @avanishmaurya2034
    @avanishmaurya2034 Před 6 měsíci

    Nice

  • @nileshsinha7869
    @nileshsinha7869 Před 2 lety

    Awesome explanation and crisp code

  • @yashtarwe6878
    @yashtarwe6878 Před rokem

    very good explanation and approach

  • @1tav0
    @1tav0 Před 2 lety

    Thank you for these series

  • @iamnottech8918
    @iamnottech8918 Před 21 dnem

    I solved this on my own using horizontal line , I was thinking that recursion will work on this came here to conform .. thanks...

  • @Kpriyasing
    @Kpriyasing Před 2 lety +1

    Amazing content!!!

  • @Rajat_maurya
    @Rajat_maurya Před rokem

    i bow my head... bhagwan apko sari khushiya de app itta bada kam free m kar rahe

  • @urdaddy8520
    @urdaddy8520 Před 9 měsíci

    Initially I was thinking to use level order traversal using deque, and then store last value of deque in our answer; can it be correct??
    I'm confused...

  • @ayushgaurabh8604
    @ayushgaurabh8604 Před 7 měsíci

    understood

  • @auroshisray6431
    @auroshisray6431 Před rokem

    well explained bhaiya!

  • @rahulrawal6542
    @rahulrawal6542 Před 2 lety

    great solution thanks :)

  • @dheepakraaj8352
    @dheepakraaj8352 Před 2 lety +15

    Understood bhaiya thank you.
    Level Order Traversal Apporach:
    During level order traversal ,we had one size variable which tells the size of queue at each level so if i==size-1; then that element is the last element of that level so we can push it into the data structure. Is this approach right bhaiya?

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

    // Level Order Traversal Variation
    // Time Complexity - O(N)
    // Space Complexity - O(N)
    class Solution {
    public:
    vector rightSideView(TreeNode* root) {
    vector res;
    if (!root) return {};
    queue q;
    q.push(root);
    while (!q.empty()) {
    int size = q.size();
    for (int i = 0; i < size; i++) {
    TreeNode* curr = q.front();
    q.pop();
    if (i == 0) res.push_back(curr->val);
    if (curr->right) q.push(curr->right);
    if (curr->left) q.push(curr->left);
    }
    }
    return res;
    }
    };

    • @adityajain1205
      @adityajain1205 Před 2 lety

      This code is for left view

    • @nikhilnagrale
      @nikhilnagrale Před 2 lety

      @@adityajain1205 bruh if you think that way, then you didn't understand the concept. Watch video again

    • @ArvindYadav-gy7fj
      @ArvindYadav-gy7fj Před 2 lety

      @@adityajain1205 i think it is for right view

  • @shaiksoofi3741
    @shaiksoofi3741 Před 15 dny

    understod

  • @anmolsingh3482
    @anmolsingh3482 Před 2 lety +1

    %Function for LeftView
    func(Node* node, int level)
    {
    if(node == NULL)
    return;
    if(level == ds.size())
    ds.push_back(node);
    func(node->left, level+1);
    func(node->right, level+1);
    }

  • @tanaykamath1415
    @tanaykamath1415 Před 2 lety +2

    I managed to solve this using an iterative approach but the soln. was complex af!, how do you manage to come up with such easy solns. 🙈🙈

  • @anishamajumder1940
    @anishamajumder1940 Před 2 měsíci

    for left side view - use preorder traversal and get the first element

  • @lifehustlers164
    @lifehustlers164 Před 11 měsíci +1

    Completed 25/54(46% done) !!!

  • @deeyasings
    @deeyasings Před 2 lety +1

    great explanation!

  • @pranav4969
    @pranav4969 Před 2 lety +3

    Even if the tree is perfectly balanced for level order, the maximum number of nodes at any level will always be less than log(N) - 1. So level order takes almost same space as recursive for balanced trees. And also level order takes less space for skewed trees. So space wise , level order is better than recursive

    • @tear7934
      @tear7934 Před rokem

      how is it log(N) - 1 can you please explain

  • @srinijabhogoju9033
    @srinijabhogoju9033 Před rokem

    Thank you bhaiya. Wonderful teacher 👏

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

    Level Order Traversal Solution for reference:
    vector rightSideView(TreeNode* root) {
    vector ans;
    if(!root) return ans;
    queue q;
    q.push(root);
    while(!q.empty()) {
    int size = q.size();
    for(int i = 0;i < size;i++) {
    TreeNode *temp = q.front();
    q.pop();
    if(i == size-1) ans.push_back(temp->val);
    if(temp->left) q.push(temp->left);
    if(temp->right) q.push(temp->right);
    }
    }
    return ans;
    }

    • @dronrahangdale2361
      @dronrahangdale2361 Před 2 lety +1

      there should right first in the for loop for rightside view rest all is correct 🙂

    • @avicr4727
      @avicr4727 Před 2 lety

      @@dronrahangdale2361 he put i= size-1 if i=0 then right should come first

    • @ScienceSeekho
      @ScienceSeekho Před rokem

      // BFS - Iterative - keeping a last variable. TC: O(N) SC: O(N)
      // -- In worst case all bottom nodes will be stored in queue, to avoid this we go with DFS
      vector rightSideView(TreeNode* root) {
      vector ans;
      if(root==NULL) return ans;

      queue q;
      q.push(root);

      while(!q.empty()) {
      int n = q.size();
      int last;
      while(n--) {
      TreeNode* tn = q.front(); q.pop();

      if(tn->left) q.push(tn->left);
      if(tn->right) q.push(tn->right);

      last = tn->val;
      }
      ans.push_back(last);
      }

      return ans;
      }

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

    for 11:49 we can keep same pre order traversal i.e first left and then right

    • @guneetgupta3356
      @guneetgupta3356 Před rokem

      for left view tree, you should go for root left right raversal

  • @VivekSharma-eh2tv
    @VivekSharma-eh2tv Před měsícem

    for the left view we, will call the recursive function for the left node and then the right node -> the logic of returning remains same but the direction of movement alters .. am i right @takeUforward

  • @shreyasvishwakarma8979
    @shreyasvishwakarma8979 Před 2 lety +1

    11:39 just exchange f ( node -> right ) and f ( left->left )

  • @jonu.1504
    @jonu.1504 Před 9 měsíci

    Recursive is easy than Iterative. Which one is good performance wise?

  • @princesahu5356
    @princesahu5356 Před 27 dny

    how will the value of level reduce

  • @harshopes
    @harshopes Před 6 měsíci

    Note to self:
    left side view call a recursve function with the root,list,level
    leftViewHelper(root.left, list, level+1);
    leftViewHelper(root.right, list, level+1);
    visaVersa for right side view

  • @maneetrajgupta
    @maneetrajgupta Před 11 měsíci +1

    correction... iterative way's space complexity can be optimized to O(H).

  • @sanskritisharma8831
    @sanskritisharma8831 Před rokem

    beautifully explained

  • @purnaanrup2394
    @purnaanrup2394 Před 2 lety +1

    can someone explain why space complexity is O(h) the data which we are storing in data structure is the output so we dont consider that, then it should be O(1) right

    • @lohitaksha244
      @lohitaksha244 Před 2 lety

      O(H) is the auxiliary space for the recursive call stack

  • @procap3578
    @procap3578 Před 6 měsíci

    why the level won't increase when we traverse the left side of the tree?

  • @PalakMittal
    @PalakMittal Před 2 lety +2

    In case anyone want iterative method 😅
    class Solution
    {
    public:
    //Function to return list containing elements of right view of binary tree.
    vector rightView(Node *root)
    {
    // Your Code here
    vectorres;
    if(!root)
    return res;
    queueq;

    q.push(root);
    while(!q.empty()){
    int n=q.size();
    for(int i=0;idata);
    }
    Node* node=q.front();
    q.pop();
    if(node->right)
    q.push(node->right);
    if(node->left)
    q.push(node->left);
    }

    }
    return res;
    }
    };
    PS: Recursive one was just mind blowing 😍😍

  • @nithishkumarreddygorre1768
    @nithishkumarreddygorre1768 Před 8 měsíci

    traverse in root,left,right

  • @ssplusultra8645
    @ssplusultra8645 Před 5 měsíci

    why arent u doing morris traversal? space would be O(1)

  • @lakshsinghania
    @lakshsinghania Před rokem

    Iterative sol for the right side view of the binary tree
    class Solution {
    public:
    vector rightSideView(TreeNode* root) {
    vector ans;
    queue q;
    q.push(root);
    if(root == NULL) return ans;
    while(!q.empty()){
    TreeNode* node = q.front();
    ans.push_back(node -> val);
    int s = q.size();
    for(int i =0; i right != NULL) q.push(node -> right);
    if(node -> left != NULL) q.push(node -> left);
    }
    }
    return ans;
    }
    };

  • @raghavkhandelwal1094
    @raghavkhandelwal1094 Před 2 lety +1

    for left view
    Instead of Reverse pre order trav. i.e, RRL take preorder trav. as the approach i.e., RLR

  • @ABHIRAMR1
    @ABHIRAMR1 Před 2 lety

    Amazing content bro!!!

  • @RupamSasmalYt
    @RupamSasmalYt Před 2 lety +1

    // Level order Traversal:
    if(root==NULL)
    return {};
    vector res;
    queue q;
    q.push(root);
    while(!q.empty()){
    int size=q.size();
    for(int i=0;ival);
    if(it->right!=NULL)
    q.push(it->right);
    if(it->left!=NULL)
    q.push(it->left);
    }
    }
    return res;

  • @divyan154
    @divyan154 Před 11 měsíci +1

    instead of reverse preorder traversal do traditional preorder and rest same

  • @Maheshmahi-fx2dr
    @Maheshmahi-fx2dr Před 2 lety

    nice approach striver

  • @ayushkushwaha171
    @ayushkushwaha171 Před rokem

    we can make use of map to solve this as well just like your previous top & bottom view questions

  • @ShubhamSahu-fe8ed
    @ShubhamSahu-fe8ed Před 2 lety

    great explanation