L37. Morris Traversal | Preorder | Inorder | C++ | Java

Поділитися
Вставка
  • Опубліковано 23 січ 2025

КОМЕНТАРІ • 300

  • @takeUforward
    @takeUforward  3 роки тому +175

    Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79
    Aaaye hi ho, toh series bhi dekh lo ;)

  • @uRamPlus
    @uRamPlus 3 роки тому +358

    Self notes:
    In-order Morris Traversal:
    🌳 1st case: if left is null, print current node and go right
    🌳 2nd case: before going left, make right most node on left subtree connected to current node, then go left
    🌳 3rd case: if thread is already pointed to current node, then remove the thread

    • @TheElevatedGuy
      @TheElevatedGuy 2 роки тому +2

      Great Job Thanks!

    • @CostaKazistov
      @CostaKazistov 2 роки тому +5

      Came here for this. Thank you! ✍👍

    • @gandhijainamgunvantkumar6783
      @gandhijainamgunvantkumar6783 2 роки тому +15

      In each video I find your comment to take the notes :)

    • @AbhishekYadav-rm4hw
      @AbhishekYadav-rm4hw 2 роки тому +7

      In 3rd case shouldn't it be Remove the thread ..and THEN PRINT NODE AND GO RIGHT??

    • @parthsalat
      @parthsalat 2 роки тому +3

      @@AbhishekYadav-rm4hw Yes, right. You can add it to 'your' notes

  • @deepanshukhanna1780
    @deepanshukhanna1780 3 роки тому +255

    Looking at the views of this video , I think this is the reason people don't make quality stuff, today's generation is more interested in watching those hypothetical motivational videos but not interested in watching what it takes to achieve your goals. Hat's off to you. Keep making such videos. Thanks a lot.

    • @KunalSinghStatus
      @KunalSinghStatus 3 роки тому +1

      Right sir ❤️

    • @vivekjaiswar6825
      @vivekjaiswar6825 3 роки тому +24

      They are more interested in "How to get into google" type of videos.

    • @01_abhijeet49
      @01_abhijeet49 2 роки тому

      Cute

    • @AdityaKumar-be7hx
      @AdityaKumar-be7hx Рік тому +1

      @@vivekjaiswar6825 True. I will also add that these are the contents of videos that actually answers the question "How to get into G?" :) By becoming truly great in solving problems

    • @thomasshelby6780
      @thomasshelby6780 6 місяців тому +5

      bro it doesn't take a lot to mind one's own business. Stop taking a jibe at others. Those guys might be good at thousand things that you aren't. Better if you quit perpetuating a rat race in tech that is there already.

  • @shriyanshjain4444
    @shriyanshjain4444 2 роки тому +13

    To be honest, this was the toughest video of the playlist so far, and obviously not the easiest!
    100/100 for the efforts!

  • @sparshsharma6068
    @sparshsharma6068 3 роки тому +63

    By far THE BEST explanation of Morris traversal on youtube!!! Maza aagya bhaiya🔥🔥 and Happy birthday bhaiya. Thank you for being the teacher and a senior we all wanted in our lives🎉🎉
    Here's the postorder morris traversal(similar to preorder), the only changes are instead of finding the rightmost node in the left subtree, we find the leftmost node in the right subtree. Also, we need to keep adding the node values in the head so as to maintain the LRN order of postorder.
    public List postorderTraversal(TreeNode root) {
    List arr = new LinkedList();
    TreeNode curr = root;
    while(curr != null){
    if(curr.right == null){
    arr.add(0,curr.val);
    curr = curr.left;
    }
    else{
    TreeNode temp = curr.right;
    while(temp.left != null && temp.left != curr)
    temp = temp.left;
    if(temp.left == null){
    temp.left = curr;
    arr.add(0,curr.val);
    curr = curr.right;
    }
    else{
    temp.left = null;
    curr = curr.left;
    }
    }
    }
    return arr;
    }

    • @kannank4269
      @kannank4269 Рік тому

      can you please explain the intuition of connecting leftmost node of right subtree to cur

    • @iamnoob7593
      @iamnoob7593 6 місяців тому

      Just replace left with right and right with left of preorder code. Thanks

    • @abhisheknag1929
      @abhisheknag1929 5 місяців тому

      @@iamnoob7593 it is wrong

  • @slowedReverbJunction
    @slowedReverbJunction 3 роки тому +116

    Seriously bhaiya
    You are man of your words
    You said that this will be the best explanation of Morris Traversal
    And you proved it
    Hats off to to bhaiya 💪👏👏
    Thank u sooo much for this awesome content ♥️♥️

  • @anmolkohli6299
    @anmolkohli6299 3 роки тому +49

    Crystal clear explanation! Understanding it from reading articles was really difficult and you made it so simple. Thank you !🙌

    • @CostaKazistov
      @CostaKazistov 2 роки тому +2

      I agree. Reading about this algorithm is one thing. Watching the explanation on UA-cam makes it soooo much clearer. 🔊

    • @imPriyansh77
      @imPriyansh77 10 місяців тому

      Yeah, you're right.@@CostaKazistov

  • @stareditz7960
    @stareditz7960 12 днів тому

    The best tutor on UA-cam.
    Thank you so much Striver.

  • @amanbhadani8840
    @amanbhadani8840 3 роки тому +9

    This is indeed the best explanation of this series, truly crystal clear.Kudos to your work for the programming community Bhaiya.

  • @harshanand4501
    @harshanand4501 3 роки тому +5

    I studied it from book but was unable to understand it. But after watching your video understood it completely. Great Explanation!

  • @paryt7696
    @paryt7696 3 роки тому +22

    1 upvote, best explaination brother, and congo for the offers from facebook and google, this news had definitely shut the mouth of haters

  • @pankajvishwakarma3124
    @pankajvishwakarma3124 6 місяців тому +7

    ✅ Postorder || Morris Traversal
    vector postorderTraversal(TreeNode* root) {
    vector postorder;
    TreeNode* cur= root;
    while(cur){
    if(!cur->right){
    postorder.push_back(cur->val);
    cur=cur->left;
    }else{
    TreeNode* prev=cur->right;
    while(prev->left && prev->left!=cur){
    prev=prev->left;
    }
    if(prev->left==NULL){
    prev->left=cur;
    postorder.push_back(cur->val);
    cur=cur->right;
    }else{
    prev->left=NULL;
    cur=cur->left;
    }
    }
    }
    reverse(postorder.begin(),postorder.end());
    return postorder;
    }

  • @JamesHalpert8555
    @JamesHalpert8555 2 роки тому +2

    Beautifully explained!! I watched another lecture but was struggling to come up with morris version for other traversals,now it's crystal clear thank you!!

  • @abhijeetmishra3804
    @abhijeetmishra3804 Рік тому +1

    In starting i was like this video need improvement but after a certain time it was STRIVER show and this was so easy to understand. Thank You Striver ...

  • @shreyanshpatil8303
    @shreyanshpatil8303 5 місяців тому +4

    DRY RUN OF THE INPUT
    Start at the Root:
    curr = 1
    Current ans = []
    First Iteration:
    curr = 1
    curr->left = 2, so we find the inorder predecessor (prev) in 2's subtree.
    Traverse prev to the rightmost node of 2's subtree:
    prev = 2 → prev->right = 5
    prev = 5 → prev->right = 6
    prev = 6
    Set 6->right = 1 (temporary link).
    Move curr = 2.
    Current ans = []
    Second Iteration:
    curr = 2
    curr->left = 4, find the inorder predecessor (prev) in 4's subtree:
    prev = 4 (rightmost node)
    Set 4->right = 2.
    Move curr = 4.
    Current ans = []
    Third Iteration:
    curr = 4
    curr->left = NULL, so append 4 to ans.
    Move curr = 2 (via 4->right).
    Current ans = [4]
    Fourth Iteration:
    curr = 2 (from temporary link)
    4->right is already set to 2, indicating the left subtree is processed.
    Remove temporary link 4->right = NULL.
    Append 2 to ans.
    Move curr = 5 (right child of 2).
    Current ans = [4, 2]
    Fifth Iteration:
    curr = 5
    curr->left = NULL, so append 5 to ans.
    Move curr = 6 (right child of 5).
    Current ans = [4, 2, 5]
    Sixth Iteration:
    curr = 6
    curr->left = NULL, so append 6 to ans.
    Move curr = 1 (via 6->right).
    Current ans = [4, 2, 5, 6]
    Seventh Iteration:
    curr = 1 (from temporary link)
    6->right is already set to 1, indicating the left subtree is processed.
    Remove temporary link 6->right = NULL.
    Append 1 to ans.
    Move curr = 3 (right child of 1).
    Current ans = [4, 2, 5, 6, 1]
    Eighth Iteration:
    curr = 3
    curr->left = NULL, so append 3 to ans.
    Move curr = NULL.
    Current ans = [4, 2, 5, 6, 1, 3]
    End:
    curr = NULL, and there are no more nodes to process.

  • @shwetanknaveen
    @shwetanknaveen 2 роки тому +12

    For post order Morris Traversal->
    We will modify the preorder morris traversal from root->left->right to root->right->left. For this we need to do one more change. While in normal preorder and inorder, we were creating thread from right most node of left subtree to present node, here we will create thread from left most node of right subtree to present node as here we have to cover right subtree before left subtree
    class Solution {
    public:
    vector postorderTraversal(TreeNode* root) {
    vector ans;
    while(root)
    {
    TreeNode *curr = root;//We will create thread from left most node of right subtree to present node and will
    //travell to that node using curr
    if(curr->right)//if root has right child
    //We can't push directly this root node val to ans as we are not sure whether we are here
    //thorough thread link after covering right subtree or we are here for the first time
    {
    curr = curr->right;
    while(curr->left && curr->left != root)//go to left most node of right subtree
    curr=curr->left;
    if(curr->left != root)//not threaded yet
    {
    ans.push_back(root->val);//it means root was visited for first time and this is modified preorder hence
    //push this node's val to ans
    curr->left = root;//create the thread
    root = root->right;//go to right to cover right subtree as modified preorder is root->right->left
    }
    else//was threaded
    {
    curr->left = NULL;//break the thread
    root = root->left;//right subtree has been covered hence now cover the left one
    //no need to push this node value as we are here for the second time using thread
    //link
    }
    }
    else//root hasn't right child
    {
    ans.push_back(root->val);//modified preorder is root->right->left hence push this value before going to left
    root = root->left;
    }
    }
    reverse(ans.begin(),ans.end());//reversing root->right->left to left->right->root to make it post order
    return ans;
    }
    };

  • @aryanchaurasia1081
    @aryanchaurasia1081 2 роки тому +2

    Amazingly explained ,the intuition has just fit into my head forever❤️

  • @adityan5302
    @adityan5302 2 роки тому +14

    Almost completed my Binary Trees trees. If I get placed in a good company, the credit goes to you. Love you bro

  • @sauravchandra10
    @sauravchandra10 Рік тому +3

    Every time I watch it, things become more clearer. This is the third time in 6 months.

  • @deepakjain4481
    @deepakjain4481 Рік тому

    you are best man no one even touch these type of topics

  • @stith_pragya
    @stith_pragya Рік тому +1

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

  • @LazyCoder20
    @LazyCoder20 4 місяці тому

    That was the best explanation.
    Truly epic bhai.

  • @santanu29
    @santanu29 2 роки тому +1

    Great Explanation. A bit of a heavy topic, takes time to wrap your head around. Will revisit after a week.

  • @sahilverma1991
    @sahilverma1991 3 місяці тому +1

    Morris Traversal for Post Order Traversal
    // postorder -> left, right, node
    // reverse of postorder is -> node right left
    // we modify Code of Morris Traversal for preorder ( which is node, left , right)
    vector ans;
    while(root){
    if(root->right == nullptr){
    ans.push_back(root->val);
    root = root->left;
    }else{
    auto temp = root->right;
    while(temp->left && temp->left != root){
    temp = temp->left;
    }
    if(temp->left == nullptr){
    temp->left = root;
    ans.push_back(root->val);
    root = root->right;
    }else{
    temp->left = nullptr;
    root = root->left;
    }
    }
    }
    reverse(ans.begin(), ans.end());
    return ans;

  • @kashishsharma6809
    @kashishsharma6809 3 роки тому +2

    Application of this algo = change links in tree ques. Eg flatten the tree ( next ques of this playlist). 👍👍

  • @mohitsingh7793
    @mohitsingh7793 2 роки тому

    Crystal and Clear Explanation for such a difficult topic❤

  • @iamnoob7593
    @iamnoob7593 6 місяців тому +1

    Superb striver , Man ur excellent

  • @Pravenkumar.D
    @Pravenkumar.D Місяць тому

    WORDS ARE NOT ENOUGH TO APRRECIATR YOU .....🔥

  • @anshumanprasad5410
    @anshumanprasad5410 3 роки тому +1

    thank you so much after struggling so much on this topic, I watched your video.

  • @saisardesai5548
    @saisardesai5548 6 місяців тому

    never seen an explaination like this wonderful!

  • @mayankdham8917
    @mayankdham8917 3 роки тому +2

    Best explanation of morris traversal..

  • @preetkatiyar969
    @preetkatiyar969 2 роки тому

    Best explanation. No one can explain better than this way.

  • @sanyummanhas1994
    @sanyummanhas1994 9 місяців тому +1

    at 4:26 what does he say a single kind of a Quadret??....i didnt quite get it, Can someone tell me what it is?

  • @umber3117
    @umber3117 Рік тому

    Best explanation.Thanks a lot for making these videos.

  • @amanali9501
    @amanali9501 2 роки тому +3

    why there is a need to remove a thread ?
    if it exists on that element it mean its left side is visited , so one can go to right directly

  • @surabhichoubey2987
    @surabhichoubey2987 2 роки тому +1

    Literally it was seems Soo horrible now it's seems so easy just because of you thanks a lot ❤️

  • @VinodKumar-by4pt
    @VinodKumar-by4pt Рік тому

    One of the easiest explanation ever, Thank you strive Bhaiya❤

  • @anmolswarnkar7707
    @anmolswarnkar7707 3 роки тому +5

    This was very well explained, thanks a lot.

  • @zsa208
    @zsa208 4 місяці тому

    Very good explanation. Appreciated

  • @shreyasnagabhushan4918
    @shreyasnagabhushan4918 2 роки тому +1

    this was amazing bro, u made the topic look like a cake walk

  • @MayankLC93
    @MayankLC93 2 роки тому +1

    such a Awesome Expalanation!!! TYSM!!

  • @Aryan-fi2qf
    @Aryan-fi2qf 2 роки тому +4

    I am getting Runtime error when trying run code without removing thread, We are moving right of curr node as we reach the rightmost of left subtree of curr node, so why do we need to remove the thread?

    • @divyansh2212
      @divyansh2212 2 роки тому +1

      We need to remove the thread because the thread pointing to the curr node and this is changing the structure of the tree

  • @bharatht5595
    @bharatht5595 2 роки тому

    Clear explanation from scratch. Thanks

  • @Ktr_792
    @Ktr_792 9 місяців тому

    Nothing Better Than this explanation

  • @aviralgoel5709
    @aviralgoel5709 2 роки тому +5

    Actual video starts @2:10

  • @shreyashachoudhary480
    @shreyashachoudhary480 2 роки тому +1

    Really amazing explanation. Thanks. Though that AMORTIZED time complexity confuses a bit.

  • @apmotivationakashparmar722
    @apmotivationakashparmar722 2 місяці тому

    Thank you So much Striver !

  • @anshumansinghrajawat7242
    @anshumansinghrajawat7242 3 роки тому +2

    Amazing explanation , keep the good work going🙌

  • @devanshtiwari9163
    @devanshtiwari9163 Рік тому

    Great Explanation till now for Morris Traversal.

  • @gandhijainamgunvantkumar6783
    @gandhijainamgunvantkumar6783 2 роки тому

    Best explanation ever. bhaiya your explaining style is very very good.

  • @studshelper9901
    @studshelper9901 7 місяців тому

    preorder : we must push curr->val in preorder before visiting left
    inorder: we will visit left then push the curr->val

  • @nagasrikuncharapu3736
    @nagasrikuncharapu3736 7 місяців тому

    It took time to understand this, but it's worth it.

  • @sumitgupta310
    @sumitgupta310 8 місяців тому

    what a amazing Explaination man!!

  • @Flash-qr5oh
    @Flash-qr5oh Рік тому

    he really made the code easy....

  • @giteshkhanna2633
    @giteshkhanna2633 2 місяці тому

    Great content.

  • @subhajyotisaha1020
    @subhajyotisaha1020 4 місяці тому

    Great video, Thanks you a lot...

  • @jaiminsolanki5478
    @jaiminsolanki5478 3 роки тому

    Complex Concept made Simple, tysm Raj Bhaiya!!!

  • @preetisahani5054
    @preetisahani5054 Рік тому

    Great! Very nicely explained!

  • @pranjalck
    @pranjalck 2 роки тому +1

    Thanks striver for making me feel like i could also think like this and approach like this...
    Thank u for Making me believe in myself 🙂❣️

  • @kaustubhdwivedi1729
    @kaustubhdwivedi1729 2 роки тому

    Every time to rescue. Thank You !

  • @rkalyankumar
    @rkalyankumar 2 роки тому

    Best explanation of Morris traversals.

  • @shineinusa
    @shineinusa 3 роки тому +1

    All I can say is thank you🙌

  • @kdoxfkck
    @kdoxfkck 3 роки тому

    best explaination ever ever..... ❤️❤️🙂🙂

  • @iffatkhan5505
    @iffatkhan5505 2 роки тому

    couldnt find a code simpler than this on tbt....thanks a ton

  • @chirag_ccp
    @chirag_ccp 2 роки тому +1

    Awesome Explanation Striver 🔥

  • @SohamDutta222
    @SohamDutta222 7 місяців тому

    YOU ARE THE BEST! THANK YOU.

  • @sathwikabhignan5535
    @sathwikabhignan5535 2 роки тому

    fantastic explanation sir it really helped me a lot😀😀

  • @vaalarivan_p
    @vaalarivan_p 2 роки тому +1

    6:00 - 11:00
    code walkthru: 14:10

  • @aviadshiber6232
    @aviadshiber6232 2 роки тому

    Damn, that is so smart technique.
    thanks for the great explanation!

  • @dishant930
    @dishant930 Рік тому

    Thank you so much Striver got it thoroughly!

  • @garvitanagpal
    @garvitanagpal Рік тому

    You're pretty good at what you do.Keep going! :)

  • @jatinsalve364
    @jatinsalve364 11 місяців тому +1

    Interviewer will ask this question like , do the traversal without using recursion or-any extraspace.

  • @riteshhhhh_01
    @riteshhhhh_01 4 місяці тому

    10:52 who is the last right guy..
    I'm bit confused

  • @ananthia5216
    @ananthia5216 Рік тому

    Awesome❤❤❤🎉

  • @omanshsharma6796
    @omanshsharma6796 8 годин тому

    understood, thank you!!

  • @TheHorseRaddish
    @TheHorseRaddish Рік тому

    Very clear explanation! Thanks!

  • @huungryyyy
    @huungryyyy 6 місяців тому

    😁😊thanku striver bhai

  • @ChillMindz_15
    @ChillMindz_15 7 місяців тому +1

    does morris traversal is also for postorder?

  • @anubhavpabby6856
    @anubhavpabby6856 2 роки тому

    Thank you bhaiya, this video helped me to learn this concept quickly

  • @vyomgoyal3125
    @vyomgoyal3125 10 місяців тому +1

    Can Postorder also be done using Morris Traversal?

  • @satyasaineelapala570
    @satyasaineelapala570 10 місяців тому

    Amazing explanation

  • @ygpointoffun9418
    @ygpointoffun9418 Рік тому

    what if striver we do not remove thread it will affect anymore??

  • @muskankalra2516
    @muskankalra2516 3 роки тому +4

    Is Morris Traversal important for interviews?

    • @imPriyansh77
      @imPriyansh77 10 місяців тому

      Yes, if the interviewer says to do some traversal in O(1) auxilliary space

    • @Anonymous____________A721
      @Anonymous____________A721 5 місяців тому +2

      Yes
      Love babbar rejected in google interview for not saying Morris traversal

  • @siddwivedi9643
    @siddwivedi9643 Рік тому +1

    nothing but respect !! Thank you bhaiya for this entire playlist

  • @Yash-uk8ib
    @Yash-uk8ib 3 роки тому +2

    sir, is it possible to do postorder with morris??

  • @satvrii
    @satvrii Рік тому

    Sucha a beautiful explanation ❤

  • @RishabhKumarRoy
    @RishabhKumarRoy 7 місяців тому

    is is important from placement pov?

  • @avibirla9863
    @avibirla9863 2 роки тому

    Loved and enjoyed a lot 🔥👍👍🔥

  • @debjitmaji632
    @debjitmaji632 2 роки тому

    Shouldn't the TC be 0(3N) .. N for whole traversal + N for making link + N for breaking link.. Plzz help!

  • @AmolGautam
    @AmolGautam Рік тому

    thank you for this explaination

  • @sawansrivastava2838
    @sawansrivastava2838 11 місяців тому

    isnt there a morris post order traversal?

  • @sudarshan3901
    @sudarshan3901 2 роки тому

    Amazing explanation !!! Loved it ...

  • @balwantyadav724
    @balwantyadav724 3 роки тому +1

    bawal 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥

  • @SatyamKumar-bw4vi
    @SatyamKumar-bw4vi 2 роки тому +1

    Hare Krishna...! Great Work

  • @morhadi
    @morhadi 8 місяців тому

    The dopamine rush after your code runs on first try >>>

  • @pranavtripathi4181
    @pranavtripathi4181 2 роки тому

    Great great great explaination🎊

  • @harshdeepak3281
    @harshdeepak3281 2 роки тому

    great explanation!!!
    loving the tree series!!!

  • @krishnakanttiwari517
    @krishnakanttiwari517 День тому

    Thank You So Much Sir

  • @Anurag_Badwahe
    @Anurag_Badwahe Рік тому

    Why not postorder using Moris Algo?

  • @rahulsrivastava9710
    @rahulsrivastava9710 3 роки тому

    Hey ! Why in morris traversal we cannot talk about space complexity O(N) , as we are taking vector to store all inorder... i didn't understand , can someone explain???

    • @rhythmbhatia8906
      @rhythmbhatia8906 3 роки тому +1

      That vector is not considered to be part of algorithmic space. It just stores the answer. Also, we can run the algorithm without it too. Think of it like this. What if instead of pushing element in vector, we just print that element. Then no space would be required.

    • @rahulsrivastava9710
      @rahulsrivastava9710 3 роки тому

      @@rhythmbhatia8906 Thankss a lot! Got it now!