L26. Print Root to Node Path in Binary Tree | C++ | Java

Поділитися
Вставка
  • Опубліковано 19 вер 2024

КОМЕНТАРІ • 255

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

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

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

      @@DeepakKumar-gv3jw no thanks, I don’t accept. Need to care of my body, its not doing well since last few days.

    • @sixth_sense_working
      @sixth_sense_working 2 роки тому +6

      inorder bolke preorder mai solution de diya

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

      @@sixth_sense_working bhai woh toh bass current node ka value check horra hai na.. vaise toh hum inorder hi jaare hain...

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

      @@takeUforward isn't it preorder???

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

      @@honeykumar5700 there is not much difference between preorder and inorder here as the place of print statement of root->val changes in both cases and that is not present here

  • @Shorts_n_Laughs
    @Shorts_n_Laughs 2 роки тому +79

    it was Preorder traversal striver. you are mentioning Inorder. BTW great explanation.

    • @bhanureddy2087
      @bhanureddy2087 6 місяців тому +3

      thank you i was doughting my understanding. i was rewatching to understand how is it inorder

    • @rushidesai2836
      @rushidesai2836 2 місяці тому +1

      Good catch @Shorts_n_Laughs

  • @fullysimplified7139
    @fullysimplified7139 3 роки тому +28

    just amazing like always
    You are still the # 1
    Greatest of all times (GOT) in algirithm explanations

  • @ornatetrout
    @ornatetrout Рік тому +9

    9:09
    One small correction
    If in question it is mentioned B is always present, then no need to check whether root is NULL or not inside solve funtion.
    Second thing is if it is not present the array ans is anyways going to be empty.
    So the code is absolutely correct irrespective of the presence of B.

  • @adityaraj1284
    @adityaraj1284 2 роки тому +106

    Bhaiya you mentioned that you are using Inorder but I thinks its preorder. Isn't it? Pardon me if am wrong because in code we are checking root first then moving on to left and right which is clearly a preorder (ROOT, LEFT, RIGHT).

  • @shubh13799
    @shubh13799 2 роки тому +10

    Will definitely watch your other series as well, so much to learn here.

  • @rishabhkumar8115
    @rishabhkumar8115 3 роки тому +3

    Greatest of all times (GOT) in algirithm explanations

  • @rushidesai2836
    @rushidesai2836 2 місяці тому +2

    Another quuestion like this is also pretty cool. Print all paths to leaf nodes.

  • @cinime
    @cinime 2 роки тому +6

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

  • @coding8000
    @coding8000 Рік тому +2

    Being, an 27 year old, @striver @takeUforward content is the only highly impacting and really changing lives of people, I saw till now, thanks BRO, love from Sweden, Europe

  • @pratyushbhatt1712
    @pratyushbhatt1712 3 роки тому +93

    This is preorder, not inorder

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

      I believe its inorder because we check the nodes value itself before traversing the left and right nodes. Thats why in the 7 case shown above we directly return true instead of checking left and right

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

      @@TechizinHD so preorder means that only we do checking and all before visiting left and right

    • @symbol767
      @symbol767 2 роки тому +7

      @@TechizinHD That is called preorder.
      Preorder = node left right
      InOrder = left node right
      PostOrder = left right node

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

      Yeah it's preorder

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

      You are right, in my opinion, Inorder is not possible in traversal, anyhow we have to visit the root before visiting it's left and right

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

    Great explanation but it is a preorder method. striver might have said it inorder by mistake.

  • @stark3585
    @stark3585 3 роки тому +17

    Good Explanation bro, please bring the DP series also ASAP as placement season has come.

  • @vatsalkudecha2746
    @vatsalkudecha2746 2 роки тому +6

    CodeStudio Problem Link: www.codingninjas.com/codestudio/problems/path-in-a-tree_3843990

  • @taranjotsingh7780
    @taranjotsingh7780 2 роки тому +23

    Hi Striver, your videos are awesome but in many videos, there's some confusion between inorder & preorder traversals. Like in this video, you said we will be using inorder (Left, Root, Right) but eventually used preorder (Root, Left, Right).

    • @imshivendra
      @imshivendra Рік тому +7

      yeah I'm also having this doubt you know I checked it again and again I thought that I am wrong but later on found that there is some mistake in video

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

      @@imshivendra Yeah even i was confused and checked the comments section and confirmed

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

      @@tarun1200 yup bro

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

      try to ignore his words bhut bar galt bol deta hai pr soln ka feel smjo bhut mst hai

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

      also dont think it is preorder or something else just see this as we neet root first forget about type of traversals they are not for smart people methods it is like spoon feeding

  • @026harshagarwal9
    @026harshagarwal9 2 роки тому +7

    Best explanation bhaiya, you are indeed a good teacher and our brother. Love ❤ you bhaiya from the bottom of my heart this series is very good and I hope that in future you also achieve great height of success 👍💯.

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

      if (getpath(root->left, arr, B) || getpath(root->right, arr, B))
      return true;
      if getpath(root->left, arr, B) returns True will it traverse through root->right ??

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

      @@devendrapatil07 No

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

      hey...can you please tell...under what name i can find this problem on leetcode?

  • @anmolagarwal5952
    @anmolagarwal5952 2 роки тому +4

    Waiting for DP series on Diwali.
    Thanks for make such awesome videos for free🔥.

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

    G.O.A.T explanation and G.O.A.T presentation bhaiii

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

    Completed 27/54 (50% done) !!!

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

    Time Complexity Doubt : Time Complexity should be O(N*H) where N is number of nodes and H is height of tree.
    Max Length of ArrayList = O(H)
    Cost of Remove function in ArrayList = O(H)
    in the worst case, that is when target is rightmost node, we would be checking each node and for removing the elements from arraylist, O(H) time is spent.
    Hence Time Complexity = O(N*H)
    Correct me if I am wrong :)

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

      remove will be O(1) because we always remove the last element from array. You can also use a stack instead, then to remove it will require stack.pop() which is O(1)

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

      @@pawansingh7430 Thanks

  • @natanshisharma8828
    @natanshisharma8828 Місяць тому

    In gfg you need to find the all leaf node path so just add a extra condition to check leaf node and add in final ans.

  • @Cool-ss7ph
    @Cool-ss7ph Рік тому

    A more beginner friendly solution that I found:
    bool path(TreeNode* node, int x, vector &ans)
    {if(node==NULL) return false;
    if(node->val==x){
    ans.push_back(node->val);
    return true;}
    bool find_lc=find(node,x,ans); //find if left child has the value if yes push back value
    if(find_lc){
    ans.push_back(node->val);
    return true;}
    bool find_rc=find(node,x,ans); //check for right child
    if(find_rc){
    ans.push_back(node->val);
    return true;}
    return false;}

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

      Can u give the question link?

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

    OMG.....Man you are just amazing. Thanks for such insightful and informative content

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

    This can also be done using iteration . Create map where we store child asindex and parent as value . Do BFS and fill the map . Then we traverse from node to root using the map and put values in a vector . Reverse the vector and return it .

  • @adityapandey23
    @adityapandey23 3 дні тому

    Understood

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

    Nicely explained but I found this one a bit complicated . Because I have solved it without complicating it using stack 😀. Followed your words that we don't need to complicate binary tree problems. Btw thanks for such a wonderful series .

  • @divyampatni3571
    @divyampatni3571 3 місяці тому

    I think the other approach is do any traversal when we get the node we require then add it to a vector return true and add every parent above.

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

    I think doing simple dfs on the whole tree while maintaining a parent array will do it. The code is much simpler

  • @AnshuSharma-h2b
    @AnshuSharma-h2b 7 місяців тому +5

    question link pls??

  • @roushankumar7684
    @roushankumar7684 8 місяців тому +1

    marvel Explanation

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

    Jzt awesomeeeeeeeeeeeeeeeeeee

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

    you are DronaCharya to every Arjun out there in DSA world !!!

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

    We can go to right first then comeback and then go to left (ROOT, RIGHT, LEFT) I guess this will also work :)

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

    it gets very easy after you see his backtracking vids 🔥🔥

  • @AmanYadav-jf1yy
    @AmanYadav-jf1yy Рік тому +7

    Code For leaf node problem:
    void solve(Node *root, vector &ans, vector &temp)
    {
    if(root==nullptr)
    return ;
    temp.push_back(root->data);
    if(root->left==nullptr and root->right==nullptr)
    ans.push_back(temp);
    solve(root->left,ans,temp);
    solve(root->right,ans,temp);
    temp.pop_back();
    }
    vector Paths(Node* root)
    {
    // Code here
    vector ans;
    vector temp;
    solve(root, ans, temp);
    return ans;
    }

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

    superb lecture and concept

  • @RupamSasmalYt
    @RupamSasmalYt 3 роки тому +6

    Bhaiya how is it In-order traversal, as we r doing root, left, right? Correct me, if i am wrong?

    • @laraibanwar1618
      @laraibanwar1618 2 роки тому +7

      its a preorder traversal,, that was what I was thinking initially. I think he said it by mistake

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

      @@laraibanwar1618 ya He mistakenly said that

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

    the solution in video is neither inorder nor preorder, we say is DFS.
    Here is my preorder Solution:
    bool rec(TreeNode* node, int x, vector &ans){
    if(!node)
    return false;
    if(node->val == x)
    return true;
    if(rec(node->left, x, ans))
    {
    ans.push_back(node->left->val);
    return true;
    }
    if(rec(node->right, x, ans))
    {
    ans.push_back(node->right->val);
    return true;
    }
    return false;
    }
    vector Solution::solve(TreeNode* A, int B) {
    vector ans;
    rec(A, B, ans);
    ans.push_back(A->val);
    reverse(ans.begin(), ans.end());
    return ans;
    }

    • @RishavRaj-kn8nm
      @RishavRaj-kn8nm 2 роки тому

      I was also thinking that how the solution in the video can be Inorder as we are processing first root and then left and right

  • @KartikeyTT
    @KartikeyTT Місяць тому

    tysm sir

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

    What you explained is not inorder traversal but a preorder traversal

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

      Can u give the question link?

  • @SuvradipDasPhotographyOfficial

    @takeUforward isn't it preorder traversal, like at every node we are processing it first and then calling the left subtree and right subtree! Anyways thanks for the awesome solution.

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

    Day 3 update: Solved two out of three sections of tree.
    Goal for day 4: Solve atleast half of difficult tree problems from a2z sheet

  • @jayeshbhanushali1745
    @jayeshbhanushali1745 2 роки тому +7

    Does it is Pre-Order ?
    correct me if I'm wrong

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

    Understooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooood, DUDE

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

      Can u give the question link?

  • @dracul_pubg5369
    @dracul_pubg5369 Місяць тому

    maja agyaa

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

    Hey Striver - You are using a PreOrder traversal

  • @tusharverma2559
    @tusharverma2559 10 місяців тому +2

    Can someone give me this question link, I can't find it

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

    you need to also add optimized approaches, iterative in above case, you just make recursive solution videos and in interview we need to come up with optimized approaches as well

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

    Thats preorder as u adding value of root then left then right

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

    I am getting a little confused. Are we implementing in-order or pre-order? At first we are considering the current root, adding it to vector, then we are going to the left and then to the right. I think this is pre order. Please correct me if I am wrong.

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

    PreOrder(root,l,r)

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

    crystal clear explanation

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 6 місяців тому

    Thank you Bhaiya

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

    bool pathtonode(vector &ans, TreeNode* root,int target){
    if(root==nullptr) return false;
    ans.push_back(root->val);
    if(root->val==target) return true;
    if(pathtonode(ans,root->left,target)||pathtonode(ans,root->right,target)) return true;
    ans.pop_back(); return false;
    } that way is very smart to write thanks

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

    Thank you sir

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

    hi viewer , Its preorder he might be busy so he told it as inorder

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

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

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

    understood

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

    We can return the node and reverse the path at end.

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

    amazing explanation sir

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

    Great explanation as always

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

    Nice work bro bas thoda kaam chillana😅😅

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

    which leetcode question is this i.e., question number

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

    @take U forward Sir I was thinking if we pass vector and NOT vector& we would not need to delete a node's value since every node will now have a local copy of this vector and we can return if we find that node else the whole recursion returns just the starting vector (which will be empty)

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

    Came up with this messy code, though this problem was easy enough, striver's videos' just help build logic of next videos(ofc spread across playlists as well)
    bool hasPath(Node *root, vector& prev, int x)
    {
    if(!root)return false;
    prev.push_back(root->data);
    if(root->data == x) return true;
    bool t1 = hasPath(root->left,prev,x);
    bool t2 = hasPath(root->right,prev,x);
    // if both subtrees do not have the node, pop the cur root
    if(!t1 and !t2) prev.pop_back();
    else return true;
    return false;// if subtree does not have the node
    }
    // function to print the path from root to the
    // given node if the node lies in the binary tree
    void printPath(Node *root, int x)
    {
    // vector to store the path
    vector prev;
    if (hasPath(root, prev, x))
    {
    for (int i=0; i

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

    isnt pre order traversal?

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

    Its a Preorder... But excellent explanation

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

    completed lecture 26 of Tree Playlist.

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

    7:47 wapas

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

    Understood

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

    great!!! could do path sum questions on leetcode with the help of this video

  • @ryzenae
    @ryzenae Рік тому +8

    My Code:
    bool getPath(Node* root, int x) {
    if(root == NULL)
    return false;
    path.push_back(root->data);
    if(root->data == x)
    return true;
    bool lh = getPath(root->left, x);
    if(lh == true)
    return true;
    bool rh = getPath(root->right, x);
    if(rh == true)
    return true;
    path.pop_back();
    return false;
    }
    in striver's code if the left half is already return's true then he'is still going to right half, did you see that if condition
    if( getPath(root->left, x) || getPath(root->right, x) )
    return true;
    in my code, if we get the left half true, then we're not going any further and directly returning the true....
    as always keep posting videos bro... Understood! So fantastic explanation as always, thank you very much!!

    • @AmanYadav-jf1yy
      @AmanYadav-jf1yy Рік тому

      You are wrong bro there is or operator in case of or operator if one condition is true then compiler not move forward to check other conditions 😊😊

  • @Mayanksingh-qp6dy
    @Mayanksingh-qp6dy 3 роки тому +1

    Even if node doesn't exist, we don't need to add an extra check since at the end it will return false and finally an empty array. Correct me if I'm wrong 😅

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

      Bro then how can we know if node exist or not and than function would not be returning true anymore 🙃

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

    preorder is the easiest, root left right is the easiest.

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

    understood,able to solve by myself

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

    At 9:55
    If I had checked for left and right in different if block , would that work , instead of checking them with OR operator ?

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

    how is that inorder ??? isnt it preorder travesal !

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

    Striver 3 should also be added to the array and then popped...right?

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

    Huge respect...❤👏

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

    thanks mate!

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

    Should it be preorder traversal ? 😅

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

    Thankyou striver

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

    Striver is a God and I'm a Dog.

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

    it should be preorder
    as in starting we considering the root before traversing to left
    can any please elaborate if i am wrong

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

    why didn't we pass the value of given Node in the function pass by reference ??

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

    Root to all nodes problem:-
    void path(Node* root, vector& res, vector& ans){
    if(root == NULL) return;
    res.push_back(root->data);
    if(root->left == NULL && root->right == NULL) ans.push_back(res);
    if(root->left) path(root->left, res, ans);
    if(root->right) path(root->right, res, ans);
    res.pop_back();
    }
    vector Paths(Node* root) {
    vector ans;
    vector res;
    path(root, res, ans);
    return ans;
    }

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

    Understood 😁

  • @Anonymous-uj3jx
    @Anonymous-uj3jx 2 роки тому

    Understood thanks :)

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

    i think it is preorder traversal?

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

    i cant find this question anywhere on any platform

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

    Understood 👍

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

    bhaiya preorder laga rhe ho. inorder nhi. video me change kardo ya description section me p.s likh do

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

    UNDERSTOOD❤

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

    Would this work if we globally define the vector arr and not pass it by reference???

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

    understoood. thanks :)

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

    Bhaiya this solution is in preorder n.....?
    Becouse we taking root first then traversing for left and right

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

    understood

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

    poland vale bhaiaaaa ...lit ho

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

    It's preorder traversal

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

    Why it is not preorder? It seems to be preorder to me