L38. Flatten a Binary Tree to Linked List | 3 Approaches | C++ | Java

แชร์
ฝัง
  • เผยแพร่เมื่อ 31 ส.ค. 2021
  • Entire DSA Course: takeuforward.org/strivers-a2z...
    Check our Website:
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    #treeSeries #striver #placements

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

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

    in 3rd approach please add this line curr->left=NULL in the if block, after curr->right=curr->left;
    if you don't it give run time error:

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

    This series is not best just because of the quality content, but also the way Striver has organized this playlist. The previous video was Morris Traversal, and this is the application of the Morris Traversal. You definitely are a gem Striver ❤

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

      same for time to burn the tree prob which requires prerequiste of count nodes at distance k prob

    • @saimanaspathapadu1299
      @saimanaspathapadu1299 8 หลายเดือนก่อน

      Arey but iss me ,when previous becomes 7, how did node changed to 6 again

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

      Yes, when I watched the burn binary tree problem & saw the way it was solved using the previous problem, my concepts became stronger.@@naveen9646

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

      @@saimanaspathapadu1299 6 ka right and left recursive call complete hua, uske baad 6 ka right set kiya as 7(prev), and 6 ka left as null. Finally, prev(last visited node) is set as 6(which is current node).

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

    How it is possible for you man! You always come up with such blowing solutions.

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

      This solutions are already available on internet... btw great explanations....

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

      Gfg pe avlble hai with same eg

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

      Isn't this available on internet ?

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

      @@vrushabh_kulye7060 yeah but nothing can beat his explanation skills.

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

      solution har jagah hai internet par magar solution samjhana mei striver bhai ka koi takkar nhi hai except Harry bhai.
      fan of both ❤❤❤❤❤❤❤

  • @samridhshubham8109
    @samridhshubham8109 5 หลายเดือนก่อน +2

    I've referred to so many channels over my lifetime, ngl...this guy is just GOAT.

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

    Your video lectures are very good and I am really thankful that you are providing us the free content.
    I think you forgot in the last pseudocode(approach 3) cur->left=NULL and due to that some of the viewers may have the confusion that's why I am writing this comment.
    Node *cur=root, *prev=NULL;
    while(cur!=NULL){
    if(cur->left!=NULL){
    prev=cur->left;
    while(prev->right){
    prev=prev->right;
    }
    prev->right=cur->right;
    cur->right=cur->left;
    cur->left=NULL; //this line
    }
    cur=cur->right;
    }
    And thanks again for such quality content.
    Edit :- Some of the viewers has already wrote this in the comment and code which you gave is also correct.

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

    Amazing explanation bhaiya! Just one doubt, I think while recording, you forgot to set the left pointers of nodes to null in morris traversal.
    Edit: The code links in the description are 100% working and correct.

  • @sameekshamurdia5-yeariddph649
    @sameekshamurdia5-yeariddph649 ปีที่แล้ว +35

    Congrats guys for completing Binary Trees, ab BST start krte h 🥳🥳
    Thank you so much striver bhaiya for the amazing series💖

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

      oof

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

      Which yr

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

      yeah kudos to you also lest keep growing with bst, graphs and dp

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

    This is what passion speaks like.Gets straight to the heart.I was finding hard to understand this concept.Thankyou so much Finally found someone to get the intuition behind algos.This is the first video of yours and subscribed right away.Just keep going.

  • @ANANDKUMAR-jk9yp
    @ANANDKUMAR-jk9yp 2 ปีที่แล้ว +9

    Striver Bhaiya, the same question was asked in my DE Shaw Interview. Unfortunately, couldn't answer that. Kaash , pahle dekh liya hota aapka yeh video. Anyways, thank you for your amazing explanation.

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

    all 3 approaches are owsome!!!! and the 3rd one using linked list blows up...superbbbbbbbbbbb

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

    You have arranged this playlist series in best order. It is really very helpful.

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

    In morris traversal code there is a small correction I think
    There should be
    curr->left = NULL;
    After, curr->right = curr->left;

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

    One of the best explanation from striver
    In Approach 3
    after if block ends add one line
    cur.left = null;
    otherwise output will be wrong as left pointer is pointing to its original left child

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

    all 3 approaches are owsome!!!! and the 3rd one using linked list blows up...superbbbbbbbbbbb
    all 3 approaches are owsome!!!! and the 3rd one using linked list blows up...superbbbbbbbbbbb

  • @Dontpushyour_luck
    @Dontpushyour_luck 9 หลายเดือนก่อน +2

    did it with morris traversal even before watching the video. you taught us so good!

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

    bro after watching your previous videos from this tree series and til 2:16 only i watched this video, i was able to come up with an approach and solved it iteratively. thanks a lot.
    Code :
    class Solution {
    public void flatten(TreeNode root) {
    TreeNode temp = root;
    if(temp == null) return;
    Deque stack = new LinkedList();

    while(temp != null || !stack.isEmpty()) {
    TreeNode prev = null;
    while(temp != null) {
    if(temp.right != null) {
    stack.push(temp.right);
    }
    temp.right = temp.left;
    temp.left = null;
    prev = temp;
    temp = temp.right;
    }

    if(!stack.isEmpty()) {
    TreeNode nextRight = stack.pop();
    prev.right = nextRight;
    temp = nextRight;
    }
    }
    }
    }

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

    literally never thought we could do this question so easily!! i am blown! that too with 3 simple approaches!

  • @stith_pragya
    @stith_pragya 3 หลายเดือนก่อน +1

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

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

    Excellent Explanation, Thank you Striver

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

    What a great explanation bro listening to your explanation reduces my repetitive writing task to remember effectively.

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

    Thank you so much sir for such a clear and detailed explanation !

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

    the 2nd solution is perfect for interview and very intuitive.

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

    whenever I face a problem in solving a problem, first choice is TUF..
    ]THANKS FOR MAKING THIS VIDEO.

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

    in the third approch there should be the
    curr.left=null
    after the curr.right=curr.left

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

      yes, good catch!

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

    Salute to your efforts for making such a wonderful series.

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

    Thank You Striver so much, after watching all the previous binary trees videos, i could do this question without watching the solution!!

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

    Nice explanation your videos are really good...please keep on making such videos...you are doing a great job.

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

    Mind Blowing Explanation ...hats off :)

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

    The main Intution for last approach is if we use normal Morris then we will loose right pointer and if we make it to root->right then a connection is made it will be not lost and also it is at its correct position

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

    I must say this is a well crafted question. THANKS

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

    cur->left should be set to NULL or else it won't change and will be not accepted as in the question it is told that the nodes in flatten BT must be set to NULL.

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

    The first approach is really amazing 👏👏👏

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

    Stack Solution can also be implemented with a Queue. Just push Left and then Right instead of Right and then Left.

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

    That evil okayyy at 7:25 lol, funny!

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

    Awesome!

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

    understood , great content, preparing for interview from it

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

    how beutiful the first approach...

  • @PrinceKumar-el7ob
    @PrinceKumar-el7ob 2 ปีที่แล้ว +1

    bow down !
    recursion is really crazy and beautiful.

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

    Great explanation. Very nicely explained.

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

    What a solid explanation man! Thanks!

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l 4 หลายเดือนก่อน

    Thank you Bhaiya

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

    Can be done by IBH(Induction-Base-Hypthesis) -
    def flatten(self, root):
    if root is None:
    return

    self.flatten(root.left)
    self.flatten(root.right)
    rL, rR = root.left, root.right
    root.left = None
    root.right = rL
    # induction
    temp = root
    while temp and temp.right:
    temp = temp.right

    temp.right = rR

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

    Guys something missing in 3rd approach after writing prev->right = curr->right curr->right = curr->left curr->left = NULL please include this line in order to break previous connections .

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

    What a gem !!

  • @ankitpalsingh8191
    @ankitpalsingh8191 9 หลายเดือนก่อน

    awesome...

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

    kya padhate ho bhai, thank you so much for the quality content!

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

    I loved the stack approach !

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

    one more thing, cur->left = nullptr; before starting iteration over next cur because it might give some kind of error

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

    Keep uploading videos keep going Thank you for this amazing contents .

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

    Was able to code it myself after watching the previous morris traversal video :)

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

    Just Wow Striver Bhaiya.......Conceptual videos are the best,code excluded.

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

    Was able to complete the binary tree series in 5 days, looking to wrap up the BST questions in the next 2-3 days.

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

    Nice solution!! Thanks for making! Morris travesal solution starts at 15:42 !!!

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

    understand this question very easily
    thanks

  • @PiyushKumar-mn3uh
    @PiyushKumar-mn3uh ปีที่แล้ว +1

    Guys, There are something missing in 3rd approach. After this line curr->right = crr->left add curr->left = NULL to break the prev connections of left O.W you will get run time error.

  • @Shivi32590
    @Shivi32590 28 วันที่ผ่านมา

    thank you

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

    In the 3rd approach i think there is an issue, we are going as right as possible, but what if the right most node has a left child?

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

    In the last approach after cur->right= cur->left ; then cur->left=NULL should be there.

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

    this reccursion will also work , normal preorder traversal, this will also take O(N) time
    Node * flattenMe(Node * root){
    if(root == nullptr) return nullptr;
    Node * leftSubtreeLinkedList = flattenMe(root->left);
    Node * rightSubtreeLinkedList = flattenMe(root->right);
    root->left = nullptr;
    root->right = leftSubtreeLinkedList;
    Node * ptr = root;
    while(ptr->right!=nullptr){
    ptr = ptr->right;
    }
    ptr->right = rightSubtreeLinkedList;
    return root;
    }

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

    In the last approac , using Morris traversal , you forgot to put curr.left= null .
    TreeNode curr=root;
    while(curr!=null){
    if(curr.left != null){
    TreeNode prev=curr.left;
    while(prev.right != null){
    prev=prev.right;
    }
    prev.right=curr.right;
    curr.right=curr.left;
    curr.left=null;
    }
    curr=curr.right;
    }

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

    Understood!
    BTW, I have created a PR with Java code for this problem. Do give it a check!

  • @avanishmaurya2034
    @avanishmaurya2034 6 หลายเดือนก่อน

    Nice

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

    Awesome explanation 🔥🔥🔥

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

    at 17:30 bro, you need to add cur->left = null as well.

  • @OmPrakash-kb2wq
    @OmPrakash-kb2wq ปีที่แล้ว +1

    best lectures on tree.

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

    Please teach us how to develop a thought process to come up with these kind of solutions.

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

      practice

  • @ANANDKUMAR-jk9yp
    @ANANDKUMAR-jk9yp 2 ปีที่แล้ว +2

    Sir, in the third approach (20:52), you are saying that you are finding the rightmost guy in the left subtree. But, initializing prev=cur->left and using the while loop may not always work. For ex:
    1
    / \
    2 4
    /
    3
    In this case, if we are at the root then the last guy in the preorder traversal of left subtree according to your algorithm will be 2 , although it should be 3. Plz correct me, if i am wrong. Although, your algorithm works on even these cases well.

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

      Yes it should be 2. Therefore 2's right will point to 4(see the code again). We will set right child of node 1 to node 2. Now we will move cur from 1 to 2. Now at node 2, what is the "rightmost guy in left sub-tree"? It is node 3. Now we will set right child of node 3 to right child of cur ; i.e right child of node2 which is 4. That's how your question is answered. Cheers !!
      Ask if you have any doubt.

    • @ShivamKumar-hf5ec
      @ShivamKumar-hf5ec 2 ปีที่แล้ว

      if the left part of curr contains only one node itself so its left is null then the prev will automatically point to curr and will not point something else

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

    Amazing. Keep making videos. You are really teaching us a lot!!

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

    Superb and thanks a lot bhaiya ❤️

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

    understooooood well. thanks :)

  • @user-nh3ov6pr3j
    @user-nh3ov6pr3j ปีที่แล้ว

    Very Good Explanation bruh!

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

    I could get the last algo on my own and felt so satisfied seeing Striver told the same method.

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

    Niceeee

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

    Awesome explanation 🙏

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

    Maza aaya! Understood ;)

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

    understood

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

    Two pointer approach in Kotlin
    fun flattenTree(head: Node?): Node?{
    var p = head
    var q = head
    while(p != null){
    if(p!!.left != null){
    q = p!!.left
    while(q!!.right != null){
    q = q!!.right
    }
    q!!.right = p!!.right
    p!!.right = p!!.left
    p!!.left = null
    } else {
    p = p!!.right
    }
    }
    return head
    }

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

    here's the 3rd approach(with correction):
    void flatten(Node *root)
    {
    //code here
    Node* curr = root;
    while(curr!=NULL){
    if(curr->left!=NULL){
    Node* prev = curr->left;
    while(prev->right){
    prev=prev->right;
    }
    prev->right=curr->right;
    curr->right = curr->left;
    curr->left=NULL;
    }
    curr=curr->right;
    }
    }

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

    In morris traversal method, u didn't make current's left pointer null

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

    Mind blowing explaination

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

    🔥🔥

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

    In the morris traversal approach, shouldn't we make the curr->left = NULL ?
    Because after doing curr->right = curr->left
    Curr is having same subtrees on both left and right so shouldn't we remove the left subtree?

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

      Do a dry run, you will see its done.

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

      Yes you need to change that curr->right = curr->left; then curr->left = NULL

  • @AditiAgarwal-rw3lq
    @AditiAgarwal-rw3lq ปีที่แล้ว

    Striver you forgot to alter the left links for all nodes :)

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

    solve this within 20 mins on my own thank you

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

      how do u approach man, I am finding things after morris traversal to be quite tough

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

      ​@@pthegreat1104 true ,same for me.
      Going straight above my head.

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

    I like stack approach 🧡🧡

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

    one word only (woow!)🙌

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

    Huge Respect...❤👏

  • @MaanyaSekhri1234
    @MaanyaSekhri1234 6 หลายเดือนก่อน

    Can someone please tell that if we are prohibited to use auxiliary data structure then can we use recursion or not ???

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

    In the first method how space complexity is O(N)...we've not made any extra ds...is this because of stack size due to function calls?

    • @shubham_v
      @shubham_v 9 หลายเดือนก่อน

      It's because each recursion call takes O(1) stack space internally. So for N number space complexity is O(N).

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

    in first approach isnt it reverse preorder and not reverse postorder?

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

    What will happen if prev is inside the flatten function?

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

    easy java Solution:
    Self explanatory: Just consider for 1 node, rest happens automatically
    class Solution {
    public void flatten(TreeNode root) {
    solve(root);
    }
    TreeNode solve(TreeNode root){
    if(root==null)
    return root;
    if(root.left==null && root.right==null)
    return root;
    TreeNode r=root.right;
    TreeNode l=root.left;
    root.left=null;
    root.right=solve(l);
    TreeNode p=root;
    while(p.right!=null){
    p=p.right;
    }
    p.right=solve(r);
    return root;
    }
    }

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

    absolute genius!!

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

    15:25 Morris Traversal

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

    Firstly thanks striver , anyone tell me why the recursive approach will have sc=O(n) , it should be O(1) .

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

      Its the function call stack memory..

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

    How about this solution
    */
    class Solution {
    public:
    TreeNode* dfs(TreeNode *root){
    if(root == NULL){
    return NULL;
    }
    TreeNode *left = dfs(root->left);
    TreeNode *right = dfs(root->right);
    TreeNode *node = root;
    node->right = left;
    while(node->right != NULL){
    node = node->right;
    }
    node->right = right;
    root->left = NULL;
    return root;
    }
    void flatten(TreeNode* root) {
    root = dfs(root);
    }

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

    Bhaiya its better to solve this with morris traversal concept

  • @AnandKumar-qj2iy
    @AnandKumar-qj2iy ปีที่แล้ว

    Striver you are just awesome

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

    '
    '
    '
    '
    '
    '
    '
    '
    void flatten(TreeNode* root) {
    TreeNode*cur=root;
    while(cur!=NULL){
    if(cur->left!=NULL){
    TreeNode*prev=cur->left;
    while(prev->right)
    prev=prev->right;
    prev->right=cur->right;
    cur->right=cur->left;
    cur->left=NULL;
    }
    cur=cur->right;
    }
    }

  • @ShubhamKumar-ex3nk
    @ShubhamKumar-ex3nk ปีที่แล้ว

    can't we use dummy node to create linked list?