Тёмный

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

take U forward
Подписаться 596 тыс.
Просмотров 178 тыс.
0% 0

Entire DSA Course: takeuforward.org/strivers-a2z...
Check our Website:
Linkedin/Instagram/Telegram: linktr.ee/takeUforward
#treeSeries #striver #placements

Опубликовано:

 

29 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 245   
@takeUforward
@takeUforward 2 года назад
Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79
@takeUforward
@takeUforward 2 года назад
@@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 года назад
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 Год назад
@@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 Год назад
it was Preorder traversal striver. you are mentioning Inorder. BTW great explanation.
@bhanureddy2087
@bhanureddy2087 3 месяца назад
thank you i was doughting my understanding. i was rewatching to understand how is it inorder
@rushidesai2836
@rushidesai2836 8 дней назад
Good catch @Shorts_n_Laughs
@shubh13799
@shubh13799 2 года назад
Will definitely watch your other series as well, so much to learn here.
@cinime
@cinime Год назад
Understood! So fantastic explanation as always, thank you very much!!
@ornatetrout
@ornatetrout 10 месяцев назад
<a href="#" class="seekto" data-time="549">9:09</a> 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.
@fullysimplified7139
@fullysimplified7139 2 года назад
just amazing like always You are still the # 1 Greatest of all times (GOT) in algirithm explanations
@alpha_coder1149
@alpha_coder1149 Год назад
goat
@shailesh_rajpurohit
@shailesh_rajpurohit 10 месяцев назад
*GOAT *ALGORITHM
@khitijkarmakar
@khitijkarmakar 8 месяцев назад
Bkl GOAT hota h
@rishabhkumar8115
@rishabhkumar8115 2 года назад
Greatest of all times (GOT) in algirithm explanations
@shubhamshah9837
@shubhamshah9837 Год назад
OMG.....Man you are just amazing. Thanks for such insightful and informative content
@rushidesai2836
@rushidesai2836 8 дней назад
Another quuestion like this is also pretty cool. Print all paths to leaf nodes.
@anmolagarwal5952
@anmolagarwal5952 2 года назад
Waiting for DP series on Diwali. Thanks for make such awesome videos for free🔥.
@roushankumar7684
@roushankumar7684 5 месяцев назад
marvel Explanation
@SagarArora1100
@SagarArora1100 2 года назад
G.O.A.T explanation and G.O.A.T presentation bhaiii
@ishanshah3309
@ishanshah3309 2 года назад
Great explanation but it is a preorder method. striver might have said it inorder by mistake.
@mukulupadhyay4656
@mukulupadhyay4656 2 года назад
Yes...
@adityaraj1284
@adityaraj1284 2 года назад
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).
@harshsinha3221
@harshsinha3221 Год назад
Yes, it's a preorder
@jatinkumar4410
@jatinkumar4410 Год назад
Yes Preorder
@vishalray4230
@vishalray4230 Год назад
yes, preorder.
@nishantchaudhari7500
@nishantchaudhari7500 Год назад
He always say inorder when he mean preorder 😅
@rohitmalhotra2566
@rohitmalhotra2566 Год назад
Yes its preorder
@stark3585
@stark3585 2 года назад
Good Explanation bro, please bring the DP series also ASAP as placement season has come.
@SHASHANKRUSTAGII
@SHASHANKRUSTAGII 2 года назад
till then watch adi verma
@026harshagarwal9
@026harshagarwal9 2 года назад
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 года назад
@@devendrapatil07 No
@yogitajoshi7218
@yogitajoshi7218 Год назад
hey...can you please tell...under what name i can find this problem on leetcode?
@lifehustlers164
@lifehustlers164 10 месяцев назад
Completed 27/54 (50% done) !!!
@coding8000
@coding8000 Год назад
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
@user-tk2vg5jt3l
@user-tk2vg5jt3l 3 месяца назад
Thank you Bhaiya
@bhaveshkumar6842
@bhaveshkumar6842 2 года назад
Great explanation as always
@shreyasnagabhushan4918
@shreyasnagabhushan4918 Год назад
crystal clear explanation
@bilalkhan2298
@bilalkhan2298 Год назад
I think doing simple dfs on the whole tree while maintaining a parent array will do it. The code is much simpler
@lavanyaprakashjampana933
@lavanyaprakashjampana933 Год назад
we love your content and we love you...🖤
@thesaurabh62057
@thesaurabh62057 Год назад
superb lecture and concept
@taranjotsingh7780
@taranjotsingh7780 Год назад
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 Год назад
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 Год назад
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
@Cool-ss7ph
@Cool-ss7ph 9 месяцев назад
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 3 месяца назад
Can u give the question link?
@divyampatni3571
@divyampatni3571 23 дня назад
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.
@AmanYadav-jf1yy
@AmanYadav-jf1yy Год назад
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; }
@samyakjain7422
@samyakjain7422 2 года назад
you are DronaCharya to every Arjun out there in DSA world !!!
@harshkanani6605
@harshkanani6605 Год назад
amazing explanation sir
@nagavedareddy5891
@nagavedareddy5891 2 года назад
Huge respect...❤👏
@trueevil2590
@trueevil2590 2 года назад
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 .
@mynk_rjpt
@mynk_rjpt 2 года назад
looks tedious
@abhishekjha4290
@abhishekjha4290 2 года назад
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 .
@Mayanksingh-qp6dy
@Mayanksingh-qp6dy 2 года назад
I too thought of solving this question using stack.
@suryakiran2970
@suryakiran2970 Год назад
Can u share the code plz
@ok-jg9jb
@ok-jg9jb Год назад
Recursion uses stack
@firebaseguy7492
@firebaseguy7492 7 месяцев назад
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
@S__Arslaan
@S__Arslaan Год назад
it gets very easy after you see his backtracking vids 🔥🔥
@PranjalGunjanDiaries
@PranjalGunjanDiaries 9 месяцев назад
Jzt awesomeeeeeeeeeeeeeeeeeee
@ayushgaurabh8604
@ayushgaurabh8604 6 месяцев назад
understood
@ommule4999
@ommule4999 4 месяца назад
Hey Striver - You are using a PreOrder traversal
@sarangtamrakar8723
@sarangtamrakar8723 2 года назад
Its a Preorder... But excellent explanation
@akashchourasiya72
@akashchourasiya72 Год назад
Thats preorder as u adding value of root then left then right
@alesblaze4745
@alesblaze4745 Год назад
thanks mate!
@Anonymous-uj3jx
@Anonymous-uj3jx 2 года назад
Understood thanks :)
@utkarshsharma6650
@utkarshsharma6650 2 года назад
understoood. thanks :)
@smitkarwatkar03
@smitkarwatkar03 Год назад
great!!! could do path sum questions on leetcode with the help of this video
@rishabhgupta9846
@rishabhgupta9846 Год назад
understood,able to solve by myself
@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.
@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)
@sirikondanaresh6387
@sirikondanaresh6387 Год назад
if u return vector in main function then it will be empty
@Sarojkumar-yh9uy
@Sarojkumar-yh9uy 2 года назад
liked!! thanx!!
@tanyacharanpahadi158
@tanyacharanpahadi158 2 года назад
Understood!
@pratyushbhatt1712
@pratyushbhatt1712 2 года назад
This is preorder, not inorder
@TechizinHD
@TechizinHD 2 года назад
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 года назад
@@TechizinHD so preorder means that only we do checking and all before visiting left and right
@symbol767
@symbol767 2 года назад
@@TechizinHD That is called preorder. Preorder = node left right InOrder = left node right PostOrder = left right node
@sailendrapavan3475
@sailendrapavan3475 2 года назад
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
@DevanshGoyal..
@DevanshGoyal.. 6 месяцев назад
What you explained is not inorder traversal but a preorder traversal
@iamweirdo4640
@iamweirdo4640 3 месяца назад
Can u give the question link?
@ayushm106
@ayushm106 2 года назад
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 Год назад
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 Год назад
@@pawansingh7430 Thanks
@sahilkumarsingh8517
@sahilkumarsingh8517 2 года назад
Understood 😁
@sauravchandra10
@sauravchandra10 11 месяцев назад
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
@arshmehta50
@arshmehta50 11 месяцев назад
Which year 4 year or 3 yr
@sauravchandra10
@sauravchandra10 11 месяцев назад
@@arshmehta50 4
@toontime7663
@toontime7663 11 месяцев назад
@@sauravchandra10 tum bhi hamari kashti me ho bhai😂
@anshulgoel1940
@anshulgoel1940 7 месяцев назад
We can return the node and reverse the path at end.
@UECAshutoshKumar
@UECAshutoshKumar 10 месяцев назад
Thank you sir
@suryanshgupta7518
@suryanshgupta7518 2 года назад
Thankyou striver
@anmolverma075
@anmolverma075 Год назад
At <a href="#" class="seekto" data-time="595">9:55</a> If I had checked for left and right in different if block , would that work , instead of checking them with OR operator ?
@krishnavamsichinnapareddy
@krishnavamsichinnapareddy 2 года назад
Understood 👍
@rohandevaki4349
@rohandevaki4349 Год назад
preorder is the easiest, root left right is the easiest.
@AbhishekKumar-td5zu
@AbhishekKumar-td5zu 2 года назад
Understood ❤️❤️❤️❤️❤️
@mriduljain1981
@mriduljain1981 Год назад
completed lecture 26 of Tree Playlist.
@herculean6748
@herculean6748 Год назад
Too good :)
@adityaramakrishnan969
@adityaramakrishnan969 2 года назад
Nice work bro bas thoda kaam chillana😅😅
@manantyagi614
@manantyagi614 Год назад
Striver 3 should also be added to the array and then popped...right?
@vatsalkudecha2746
@vatsalkudecha2746 2 года назад
CodeStudio Problem Link: www.codingninjas.com/codestudio/problems/path-in-a-tree_3843990
@adarshgupta2262
@adarshgupta2262 Год назад
Leetcode question no. ??????????????????????????
@vatsalkudecha2746
@vatsalkudecha2746 Год назад
@@adarshgupta2262 257
@yogitajoshi7218
@yogitajoshi7218 Год назад
@@vatsalkudecha2746 no..they are not same
@adarshkumarrao3478
@adarshkumarrao3478 Год назад
UNDERSTOOD❤
@dreamyme543
@dreamyme543 Год назад
Understood:)
@user-xu1rv3uf5o
@user-xu1rv3uf5o 4 месяца назад
question link pls??
@jayeshbhanushali1745
@jayeshbhanushali1745 2 года назад
Does it is Pre-Order ? correct me if I'm wrong
@avtarchandra2407
@avtarchandra2407 2 года назад
poland vale bhaiaaaa ...lit ho
@altamashsabri8142
@altamashsabri8142 Год назад
Understood
@coding8000
@coding8000 Год назад
Understooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooood, DUDE
@iamweirdo4640
@iamweirdo4640 3 месяца назад
Can u give the question link?
@RupamSasmalYt
@RupamSasmalYt 2 года назад
Bhaiya how is it In-order traversal, as we r doing root, left, right? Correct me, if i am wrong?
@laraibanwar1618
@laraibanwar1618 2 года назад
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
@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
@hrishikeshbakshi8961
@hrishikeshbakshi8961 10 месяцев назад
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.
@yashtripathi5995
@yashtripathi5995 10 месяцев назад
U r correct.... he said inorder by mistake
@Mayanksingh-qp6dy
@Mayanksingh-qp6dy 2 года назад
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 🙃
@pranshumehta3228
@pranshumehta3228 2 года назад
Should it be preorder traversal ? 😅
@naveensaicremsiyadlapalli3769
It's preorder traversal
@sejalrai30
@sejalrai30 2 года назад
sir you r awesome...pr ye relevel vali cheez sun sun kr dimag khraab hota h
@satyamdubey704
@satyamdubey704 2 года назад
Bhaiya this solution is in preorder n.....? Becouse we taking root first then traversing for left and right
@jayyy311
@jayyy311 Год назад
💚
@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
@cypher7536
@cypher7536 2 года назад
i think it is preorder traversal?
@your_name96
@your_name96 2 года назад
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
@prateek_jakhar
@prateek_jakhar Год назад
Good bhai
@TheBillionairesWorld
@TheBillionairesWorld Год назад
how is that inorder ??? isnt it preorder travesal !
@abhisheksinghchauhan5169
@abhisheksinghchauhan5169 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
@nitishprasadkushwaha
@nitishprasadkushwaha 2 года назад
god level
@ujjwalkapil09
@ujjwalkapil09 2 года назад
which leetcode question is this i.e., question number
@tusharverma2559
@tusharverma2559 7 месяцев назад
Can someone give me this question link, I can't find it
@momilijaz271
@momilijaz271 2 года назад
done!
@venutalla5932
@venutalla5932 Год назад
Tq sir
@satyamroy3783
@satyamroy3783 Год назад
striver u 💥
@ishikacasley2786
@ishikacasley2786 2 месяца назад
why didn't we pass the value of given Node in the function pass by reference ??
@satvrii
@satvrii Год назад
❤❤❤❤❤
@imranimmu4714
@imranimmu4714 11 месяцев назад
isnt pre order traversal?
@soumikdutta7867
@soumikdutta7867 2 года назад
Isn't it Preorder? Correct me if I'm wrong
@DSrikanthd
@DSrikanthd 2 года назад
Everything is good, but it seems like this is Preorder.
@soumyajitmishra6855
@soumyajitmishra6855 Год назад
Why it is not preorder? It seems to be preorder to me
@siddhanttyagi6653
@siddhanttyagi6653 2 года назад
bhaiya preorder laga rhe ho. inorder nhi. video me change kardo ya description section me p.s likh do
Далее
L25. Check for Symmetrical Binary Trees | C++ | Java
9:20
КВН 2024 Высшая лига Четвертая 1/4
1:52:57
Never waste PASTA SAUCE @itsQCP
00:19
Просмотров 6 млн
Sum Root to Leaf Numbers | Recursion | Leetcode #129
10:17
5.5 Math Books For Self Made Mathematicians
25:50
Просмотров 19 тыс.
8 patterns to solve 80% Leetcode problems
7:30
Просмотров 203 тыс.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Print all ROOT to LEAF paths in a binary tree
13:37
Просмотров 40 тыс.
L5. Jump Game - II | Greedy Algorithm Playlist
16:45
Просмотров 11 тыс.
КВН 2024 Высшая лига Четвертая 1/4
1:52:57