Binary Tree Inorder Traversal | Morris Traversal | Leetcode-94

Sdílet
Vložit
  • čas přidán 5. 09. 2024
  • Whatsapp Community Link : www.whatsapp.c...
    This is the 33rd Video of our Binary Tree Playlist.
    In this video we will try to solve an easy problem Inorder Traversal using Morris Traversal - Binary Tree Inorder Traversal (Leetcode -94).
    I will explain the intuition so easily that you will never forget and start seeing this as cakewalk EASYYY.
    We will do live coding after explanation and see if we are able to pass all the test cases.
    Also, please note that my Github solution link below contains both C++ as well as JAVA code.
    Problem Name : Binary Tree Inorder Traversal
    Company Tags : Lots of companies
    My solutions on Github(C++ & JAVA) : github.com/MAZ...
    Leetcode Link : leetcode.com/p...
    My DP Concepts Playlist : • Roadmap for DP | How t...
    My Graph Concepts Playlist : • Graph Concepts & Qns -...
    My GitHub Repo for interview preparation : github.com/MAZ...
    Subscribe to my channel : / @codestorywithmik
    Instagram : / codestorywithmik
    Facebook : / 100090524295846
    Twitter : / cswithmik
    Approach Summary :
    The given code implements an in-order traversal of a binary tree without using recursion or additional space for a stack. It employs Morris Traversal, a space-efficient algorithm that modifies the structure of the tree temporarily during the traversal.
    The main idea is to establish a temporary link between a node and its in-order predecessor by threading some of the null pointers in the tree. The algorithm iterates through the tree, adding nodes to the result vector in the correct order. If a node has a left child, it finds the rightmost node in its left subtree, connects it to the current node, and then moves to the left child. This process continues until a node with no left child is encountered, at which point it is added to the result, and traversal moves to the right child. The process is repeated until the entire tree is traversed in an in-order fashion.
    This Morris Traversal approach allows for in-order traversal with O(1) space complexity, making it particularly useful in situations where minimizing space usage is crucial.
    ╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
    ║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
    ╠╗║╚╝║║╠╗║╚╣║║║║║═╣
    ╚═╩══╩═╩═╩═╩╝╚╩═╩═╝
    ✨ Timelines✨
    00:00 - Introduction
    #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge #leetcodequestions #leetcodechallenge #hindi #india #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge#leetcodequestions #leetcodechallenge #hindi #india #hindiexplanation #hindiexplained #easyexplaination #interview#interviewtips #interviewpreparation #interview_ds_algo #hinglish #github #design #data #google #video #instagram #facebook #leetcode #computerscience #leetcodesolutions #leetcodequestionandanswers #code #learning #dsalgo #dsa

Komentáře • 56

  • @jkunal
    @jkunal Před 9 měsíci +17

    Finally Morris Traversal. Thanks MIK

  • @lofireverbz-wy7go
    @lofireverbz-wy7go Před 6 měsíci +7

    in case agr kisi ko preorder ka code chaiye to than
    only minor change in same format only 2 line change
    class Solution {
    public:
    vector preorderTraversal(TreeNode* root) {
    vector result;
    TreeNode* curr = root;

    while (curr!=NULL) {

    if (curr->left ==NULL) {
    result.push_back(curr->val);
    curr = curr->right;
    } else {
    TreeNode* leftchild = curr->left;

    while (leftchild->right!=NULL) {
    leftchild=leftchild->right;
    }

    leftchild->right = curr->right; // right last node ko current ke right se jodo kuuki humne curr ko print kra lia hai i,e preorder
    TreeNode* temp = curr;
    result.push_back(curr->val); // connection break krne se phle curr ko store krlo
    curr = curr->left;
    temp->left = NULL;
    }
    }
    return result;
    }
    };

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

      bro can you tell for this traversal why this thing is required temp->left = NULL;
      because we are pointing to the right of curr, so no matter we have left pointer to the curr we won't go to that node we will move to its right node.

    • @lofireverbz-wy7go
      @lofireverbz-wy7go Před měsícem +1

      @@word___addict8768 if you don't make temp->left=NULL than for practical thing draw a tree
      than if you go left of the tree and when you reach at left's NULL than than it will send curr to right and now you start traversing than again curr will have option to go to left and jabki aisa nhi hona chaiye kuuki tumne usse answer mai daaldia and infinite loop mai fasjaega
      I hope you understand now, sorry for late reply

  • @Momentsofmagic28
    @Momentsofmagic28 Před 9 měsíci +1

    The comments on your videos are clear proof how good you are. You are undoubtedly one of most influential and amazing tutors I have ever seen.

  • @ugcwithaddi
    @ugcwithaddi Před 9 měsíci +1

    You were right, Dry run is one of the most underrated skill.
    Thanks a lot legend 🙌🙌🙌

  • @user-gg1fz6uv5v
    @user-gg1fz6uv5v Před 9 měsíci +7

    Jaha MIK sir hai waha daily kuchh na kuchh shikhne ko milega

  • @user-ub2is4rs4x
    @user-ub2is4rs4x Před 9 měsíci +2

    Mast samjhate ho sir aap 🔥🔥🔥
    Thanks from my whole college friends and me

  • @wearevacationuncoverers
    @wearevacationuncoverers Před 9 měsíci +2

    Everyday you teach me something.
    Thank you so so much MIK
    (Is baar wala Thumbnail mast hai)

  • @Tjr00011
    @Tjr00011 Před 2 měsíci +1

    Better than best one (strivers) both are very helpful

  • @deepakdass4710
    @deepakdass4710 Před 9 měsíci +2

    Thanks for teaching this concept sir. Although this technique is not using space, but it manipulates the tree itself. That's only the problem ig. But no problem when manipulation is allowed.
    Thanks a lot sir 😊😊

    • @codestorywithMIK
      @codestorywithMIK  Před 9 měsíci +1

      Yes you are absolutely right 😇🙏❤️
      Thank you for watching 🙏

  • @raisanjeeb42
    @raisanjeeb42 Před 8 měsíci +1

    Thank you bhaiya for this wonderful explanation!
    Best Explanation for morris order one could find on CZcams ❤

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

    Liked the explanation ❤

  • @basujain8928
    @basujain8928 Před 2 měsíci +3

    bhai striver se jyafa accha padhate ho

  • @technologicalvivek7510
    @technologicalvivek7510 Před 5 měsíci +1

    Bahut badiya samjhate ho bhaiya aap. maza aa jata hai.
    bhaiya mein gate 2024 qualify ho gya.

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

      Thank you ❤️
      And congratulations brother. Proud moment 😇❤️

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

    Mene babbar bhaiya se iska lecture dekha tha ...aisa lg rha tha ratlo baat khtm ...babbar bhaiya be like --(hmare yha aise hi hota h))😂😂
    Aaj jaakr samj aaya kya kar rhe h kyu kar rhe h thanks brother ❤

  • @secretvibz6300
    @secretvibz6300 Před 4 měsíci +1

    So far the best video omn this topic

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

    it is very clear now, thanks a lot

  • @Cpp_Algo
    @Cpp_Algo Před 5 měsíci +1

    Thank_you_so_Much sir for your explanation .

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

    bhai kya samjhaya h yr gjb

  • @rohitshah8904
    @rohitshah8904 Před 9 měsíci +12

    Meanwhile me thinking aaj ke question mai kuch sikhne layak nahi hai

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

    MIK made it easy henceforth it's MIK Traversal.

  • @ntsequalifier341
    @ntsequalifier341 Před 29 dny +1

    Other's praise babbar or Striver for their videos but I don't like their solution because they don't explain in lay man terms like striver( with poor english and fast pace) just completes the solution code anyhow whereas babbar does not have a proper way of teaching so I feel this guy will have a better base as he explains well.

  • @dayashankarlakhotia4943
    @dayashankarlakhotia4943 Před 9 měsíci +1

    Revise Morris traverse
    Thanks again 🎉❤

  • @saurabhKumar-hj6yp
    @saurabhKumar-hj6yp Před 9 měsíci +3

    ❤❤

  • @aws_handles
    @aws_handles Před 9 měsíci +1

    amazing explanation

  • @dhruvsanghvi5562
    @dhruvsanghvi5562 Před 7 měsíci +1

    It helped mem a lot , tysm sir

  • @anuppatankar4294
    @anuppatankar4294 Před 9 měsíci +1

    Great video 👌🏻

  • @tutuimam3381
    @tutuimam3381 Před 9 měsíci +1

    Amazing ❤❤

  • @nk-fs8bj
    @nk-fs8bj Před 9 měsíci +1

    amazing🙃

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

    bhaiya aaj ka biweekly contest ka yeh graph ka question please samjha dijiye please....Number of Possible Sets of Closing Branches.....

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

    0:07 Hamarey liye sub kathin h 😅🤣, aap pudhao brother 😇

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

    can u please modify the same code to do preorder and post order. If yes how?

  • @Singh_5454
    @Singh_5454 Před 11 dny

    Bhaiya preorder and post order ka bhi code comment me reply kr do please

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

    Iss logic se pre-order traversal kaise karu bhaiyaa?

    • @EB-ot8uu
      @EB-ot8uu Před 4 měsíci

      void morrisTraversalPreorder(node* root)
      {
      while (root)
      {
      // If left child is null, print the current node data. Move to
      // right child.
      if (root->left == NULL)
      {
      coutright && current->right != root)
      current = current->right;

      // If the right child of inorder predecessor already points to
      // this node
      if (current->right == root)
      {
      current->right = NULL;
      root = root->right;
      }

      // If right child doesn't point to this node, then print this
      // node and make right child point to this node
      else
      {
      cout

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

      @@EB-ot8uu No I found this one, but sir ne jis logic se bataya uss logic se pre-order and postorder kaise hoga??

    • @vinayn0707
      @vinayn0707 Před 3 měsíci +2

      @@suvankar54 slight modification from inorder code will get a preorder
      void morisPreorder(TreeNode* root, vector &ans)
      {
      TreeNode * curr = root;

      while(curr != NULL)
      {

      if(curr->left == NULL)
      {
      ans.push_back(curr->val);
      curr = curr->right;
      }
      else
      {

      ans.push_back(curr->val);
      TreeNode *childNode = curr->left;
      while(childNode->right != NULL)
      {
      childNode = childNode->right;
      }
      // instead of cur , point to curr->right , this is change from inorder to preorder change .
      childNode->right = curr->right;
      TreeNode *temp = curr;
      curr = curr->left;
      // set temp->right to NULL , in inorder temp->left was set to NULL .
      temp->right = NULL;

      }
      }

  • @sanjaykatta6499
    @sanjaykatta6499 Před 9 měsíci +1

    Bro, will the system's stack be counted while calculating the space complexity? Because I see that when I submitted using the recurisve approach - the space used was less (very minute difference though) compared to the morris traversal.
    Update : same code submission on leetcode shows different space complexity on each submission. Not sure why this happens.
    On submitting again - I see that morris traversal took less space.

    • @codestorywithMIK
      @codestorywithMIK  Před 9 měsíci +1

      Ya actually it happens. It’s something with leetcode servers behind the scene.

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

    Sir, ye to GOLD hai

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

    if(root != NULL){
    inorderTraversal(root->left);
    ans.push_back(root->val);
    inorderTraversal(root->right);
    }
    return ans;

  • @shafiquemohammad2876
    @shafiquemohammad2876 Před 5 měsíci +1

    Bhai tumne tree modify kr dia h. Ye sahi nhi h. Leetcode me pass hojayega but this is not acceptable in interviews.

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

      Definitely. It’s not acceptable in interviews.
      This video is only for the purpose of Teaching Morris Traversal. ❤️
      Only if the interviewer allows you to modify the tree, then only apply morris else not.

    • @shafiquemohammad2876
      @shafiquemohammad2876 Před 5 měsíci +2

      @@codestorywithMIK Agree with the first part, but as for the second, we can actually write morris traversal to preserve the original tree structure. See Striver's solution for the same.
      Anyways, this video is also great! Thanks.

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

      Definitely. Thank you for your valuable feedback 😇❤️

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

    I'm just amazed by his explanation. He's truly a gem, so underrated @codestorywithMK