L11. Iterative Postorder Traversal using 2 Stack | C++ | Java | Binary Tree

  Рет қаралды 237,852

take U forward

take U forward

Күн бұрын

Пікірлер: 207
@takeUforward
@takeUforward 3 жыл бұрын
Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79 Please watch it at 0.5x or 0.75x, I mistakenly uploded at 2x 🥺
@rajasethi2341
@rajasethi2341 3 жыл бұрын
Actually i was watching at 1.75X and suddenly everything changes
@democratcobra
@democratcobra 3 жыл бұрын
Great Explaination...Thanks for uploading....
@someone-zi8xc
@someone-zi8xc 3 жыл бұрын
@@rajasethi2341🤣
@preetamkumar838
@preetamkumar838 2 жыл бұрын
I watched it whole at 1.5x and realized, later i read the comments 😂😂
@ARUN-ik2nb
@ARUN-ik2nb 2 жыл бұрын
@@rajasethi2341 me too🤣
@codermal
@codermal 2 жыл бұрын
We can also see it as preorder-> root left right swap left, right -> root right left reverse -> left right root So in first stack we apply pre-order traversal code, and 2 stack is to reverse it, basically we need 2 stack as we can't move from child to parent in tree
@ashtonronald
@ashtonronald 4 ай бұрын
Thanks! Really helpful!!
@harshitmalhotra8627
@harshitmalhotra8627 3 жыл бұрын
This year's only video I have watched at 0.5x.
@CosmicWhale7777
@CosmicWhale7777 2 жыл бұрын
yes haha
@omkarshendge5438
@omkarshendge5438 2 жыл бұрын
same lol
@shortsmaker0308
@shortsmaker0308 2 ай бұрын
Same 😁
@theSeniorSDE
@theSeniorSDE 3 жыл бұрын
Striver, had to slow down the video speed to understand it better. 😂 Completed this as well. Steps : 1. initial config : Take the root and put it in the 1st stack. 2. Now, take the top from the 1st stack and put it into the 2nd stack 3. After that, if the top in 2nd stack has left → add it in 1st stack. And if the top in 2nd stack has right → add it in the 1st stack. 4. Now again, take the top from the 1st stack and put it into the 2nd stack. Repeat step 2 & 3 untill 1st stack is empty. 5. Pop the element from the 2nd stack and print.
@takeUforward
@takeUforward 3 жыл бұрын
Yeah by mistakenly, i uploded it at 2x 😂
@aditiranjan303
@aditiranjan303 2 жыл бұрын
Thanks for writing the steps clearly
@rigaut-valorant6105
@rigaut-valorant6105 Жыл бұрын
@@takeUforward and I still watched it at 1.5x
@vishalplayzz2580
@vishalplayzz2580 Жыл бұрын
@@rigaut-valorant6105 Lmao
@ChefnCoder
@ChefnCoder Жыл бұрын
u explained it really good, any chances u have made notes of tree series cause i am sure it will be really good
@JayPanchal03
@JayPanchal03 2 ай бұрын
Understood the concept first and then wrote the code on my own and later found out that it is exactly same as in the video got confidence....
@SaurabhSingh-nv9jj
@SaurabhSingh-nv9jj 2 жыл бұрын
we can also use the ans vector which we are going to return as the second stack, but in the end we will have to reverse the vector before returning it.
@namanchhabra4136
@namanchhabra4136 7 ай бұрын
In Stack 1 we make ROOT RIGHT LEFT ( like we did in preorder -> root left right ) Stack2 is used for reverse : - if we reverse the Stack1 it will give Postorder which is LEFT RIGHT ROOT
@tanishq2766
@tanishq2766 Жыл бұрын
I was not at all able to come up with this, I hardly give up on problems, this was impossible for me to think fr!
@mohit7717
@mohit7717 5 ай бұрын
You can make everyone understand in 2x too .. that's the quality in you.. Great man!
@26_jamkhandedattatray59
@26_jamkhandedattatray59 2 жыл бұрын
i shocked when i played this video at 1.75x speed, after read out description I understand what actually happened😂. Anyway but lec is awsome
@Shourya_performs
@Shourya_performs 2 жыл бұрын
xctly
@codding32world50
@codding32world50 2 жыл бұрын
Same here lmao
@Lakshya-f4l
@Lakshya-f4l 5 ай бұрын
😂😂
@valiz2628
@valiz2628 Жыл бұрын
explanation is so beautiful , so elegant , just looking like a wow
@devanshmesson2777
@devanshmesson2777 2 жыл бұрын
Those who are unable to understand the intuition behind this, Watch the next video which uses 1 stack, That video is relatively intuitive.
@stith_pragya
@stith_pragya 6 ай бұрын
UNDERSTOOD...Thank You So Much for this wonderful video..........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@605_samikrdas4
@605_samikrdas4 3 жыл бұрын
in c++ code: vector inOrder(Node* root) { vector ino; stack s; Node* p =root; while(true) { if(p!=NULL) { s.push(p); p=p->left; } else { if(s.empty()==true) break; p=s.top(); s.pop(); ino.push_back(p->data); p=p->right; } } return ino; }
@DevanshuAugusty
@DevanshuAugusty Жыл бұрын
what is the intution behind this solution...you are directly junmping to the solution
@letsrock7354
@letsrock7354 2 жыл бұрын
Rather than taking a stack we can save that in the resultant vector and then reverse it in the end We can save some space
@iamsalonitayal
@iamsalonitayal 3 жыл бұрын
I was already watching ur vids at 1.5x . But here:-) for a moment I thought my mind was processing the content slowly. lol. Anyways awesome lectures.
@lifehustlers164
@lifehustlers164 Жыл бұрын
Completed 12/54(22% done) !!!
@nandkishor999
@nandkishor999 2 жыл бұрын
hello sir this series is really great. I tried many series on the youtube but your's one is best thank you so much.
@K_EN_VisheshSaini
@K_EN_VisheshSaini Жыл бұрын
We can just use the preorder traversal code and reverse the insertion of left and right nodes in the stack and also the array in the end before returning it. Code:- class Solution { public: vector postorderTraversal(TreeNode* root) { vector ans; if(root == NULL) return ans; stack st; st.push(root); while(!st.empty()){ TreeNode *temp = st.top(); st.pop(); ans.push_back(temp->val); if(temp->left!=NULL) st.push(temp->left); if(temp->right!=NULL) st.push(temp->right); } reverse(ans.begin(), ans.end()); return ans; } };
@bambu-mq9zg
@bambu-mq9zg 2 жыл бұрын
we can also use queue and stack for it... like root >right>left then store it into queue from left class Solution: # Return a list containing the inorder traversal of the given tree def postOrder(self,node): s=[node] l=1 ans=deque() while l!=0: a=s.pop() l-=1 ans.appendleft(a.data) if a.left!=None: s+=[a.left] l+=1 if a.right!=None: s+=[a.right] l+=1 ans=list(ans) return ans
@Rebantaprat
@Rebantaprat 2 жыл бұрын
Striver what is the intuition for using 2 stack 🤔?
@tonyconor681
@tonyconor681 2 жыл бұрын
I puted as usual 2x then suddenly I feel it's like 3x , then I did 1.25 final calmly understood his words holy moly
@pranjal1100
@pranjal1100 3 жыл бұрын
Was watching the playlist at 1.35x when I came across this XD
@AnkurSingh-cv1ls
@AnkurSingh-cv1ls Жыл бұрын
We actually don't require second stack.....as shown here: vector postorderTraversal(TreeNode* root) { if(root==NULL) return {}; stack st1; vector ans; st1.push(root); while(!st1.empty()){ TreeNode* temp=st1.top(); st1.pop(); if(temp->left!=NULL) st1.push(temp->left); if(temp->right!=NULL) st1.push(temp->right); ans.push_back(temp->val); } reverse(ans.begin(),ans.end()); return ans; }
@ManyaNayak-md7xr
@ManyaNayak-md7xr 6 ай бұрын
it will give tle
@viveksingh_01
@viveksingh_01 3 ай бұрын
@@ManyaNayak-md7xr it will not
@prabhakaran5542
@prabhakaran5542 4 ай бұрын
Understood ❤
@neelgorasiya7199
@neelgorasiya7199 2 жыл бұрын
I used to watch your videos 1.5x. But when I did it in this video Ahhhh!! NFS rocks........
@nihalshukla7718
@nihalshukla7718 3 жыл бұрын
I was refreshing again refreshing then open in new tab.. after that I came to comment section.. then I realize my pc is working fine.
@bhavkushwaha
@bhavkushwaha 7 ай бұрын
Thankyou Striver, Understood!
@andersonbhat6885
@andersonbhat6885 3 жыл бұрын
Striver bhaiya as a first timer looking at this algo i'm not sure whether we should be able to think of such an algo on our own ,cause i couldn't think of it or are we expected to get this after some practice ?
@takeUforward
@takeUforward 3 жыл бұрын
There are certain things you have to know in order to do.
@justarandomguy6106
@justarandomguy6106 2 жыл бұрын
@@takeUforward means we have to remedy these types of solution like algorithm
@samuelfrank1369
@samuelfrank1369 Жыл бұрын
UNDERSTOOD. THANKS A LOT.
@raj-nq8ke
@raj-nq8ke 2 жыл бұрын
begins at 0:44
@arnabdutta4662
@arnabdutta4662 2 жыл бұрын
if stack 2 is made integer dayatype then space requirement would be reduced :)
@raviketan2957
@raviketan2957 3 жыл бұрын
Thanks for whatever u r doing.
@5076_GidijalaDineshSurya
@5076_GidijalaDineshSurya 2 ай бұрын
Loved the lecture striver! I have a doubt, Why not just use a vector instead of 2nd stack and then reverse it? Why did we use 2 stacks?
@piyushmahale9024
@piyushmahale9024 4 ай бұрын
This is the first video that i have seen at normal speed 😂
@ritamkabiraj8035
@ritamkabiraj8035 Жыл бұрын
st2.push(node) instead st2.add(node) [Time 3:09]
@liteni368
@liteni368 2 жыл бұрын
Striver bhaia tussi great ho
@AnkitOli-d2g
@AnkitOli-d2g Жыл бұрын
Can we directly add the elements to output arrayList and print it in reverse order,without using st2. Will it make space complexity a bit efficient?
@rupalikumari8829
@rupalikumari8829 5 ай бұрын
Understood : )
@mriduljain1981
@mriduljain1981 Жыл бұрын
completed lecture 11 of Tree playlist.
@alienx2367
@alienx2367 3 жыл бұрын
Why did you suddenly tuned into Eminem
@ishankbansal9239
@ishankbansal9239 3 жыл бұрын
😂🤣
@shubamgoswami
@shubamgoswami 3 жыл бұрын
EMINEM IS RAP GOD AND STRIVER IS INTIUATION GOD
@nawabkhan4916
@nawabkhan4916 2 жыл бұрын
great work, and have lots of sponsor ad so that you can provide great videos.
@mannmehta4841
@mannmehta4841 Ай бұрын
Easier approach with only one stack without infinite loop, but yes O(N) extra space - Code: void inordere_traversal_interative(Node* root) { stack st; st.push(root); unordered_map vis; while(!st.empty()) { Node* node = st.top(); if (node->left != NULL and !vis[node->left]) { st.push(node->left); continue; } if (node->right != NULL and !vis[node->right]) { st.push(node->right); continue; } cout
@parthh1112
@parthh1112 7 ай бұрын
void inorder(TreeNode *&root) { stack s1, s2; s1.push(root); while (s1.size() > 0) { TreeNode *x = s1.top(); s2.push(x); s1.pop(); if (x->left) s1.push(x->left); if (x->right) s1.push(x->right); } while (s2.size() > 0) { cout val
@debangshubanerjee1311
@debangshubanerjee1311 2 жыл бұрын
What is the intuition behind using 2 stacks?
@subhajitdey135
@subhajitdey135 Жыл бұрын
In Preorder and inorder we were going from parent to child but as you can see in postorder we need to keep the track of parent before moving to the right child. So to keep the track we are using two stacks.
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@t-anime517
@t-anime517 2 жыл бұрын
Understood😊
@rishidubey5037
@rishidubey5037 Жыл бұрын
Great Content.
@jasonbrody4618
@jasonbrody4618 3 жыл бұрын
Liked. Cfbr will watch after some time
@apmotivationakashparmar722
@apmotivationakashparmar722 Ай бұрын
Thank you so much.
@ARUN-ik2nb
@ARUN-ik2nb 2 жыл бұрын
Short and sweet 👌
@rishabhshairy972
@rishabhshairy972 Ай бұрын
We can use One Stack and One List List can be used to store values and return public List postorderTraversal(TreeNode root) { List postOrderList = new ArrayList(); if (root == null) { return postOrderList; } Stack opStack = new Stack(); opStack.push(root); while (!opStack.isEmpty()) { root = opStack.pop(); if (root.left != null) { opStack.push(root.left); } if (root.right != null) { opStack.push(root.right); } postOrderList.add(root.data); } Collections.reverse(postOrderList); return postOrderList; }
@smitdumore1064
@smitdumore1064 2 жыл бұрын
Making the video duration short by speeding it up is a genius strategy to get more clicks,
@snehilsinha5624
@snehilsinha5624 2 жыл бұрын
Why don't we store the postorder traversal in the final output vector itself and reverse it at the last rather than using an extra stack for reversal ?
@vakhariyajay2224
@vakhariyajay2224 Жыл бұрын
Thank you very much. You are a genius.
@akashverma5756
@akashverma5756 4 ай бұрын
what is intuition behind this solution? I think this solution is inspired from from the fact that post order traversal is opposite of reverse preorder traversal. (left - right - node) == !(node - right - left)
@DeadPoolx1712
@DeadPoolx1712 Ай бұрын
UNDERSTOOD;
@lourduradjou182
@lourduradjou182 Жыл бұрын
super hero striver
@anshikagupta5858
@anshikagupta5858 11 ай бұрын
Thankyou Striver:)
@rishabmalhotra6980
@rishabmalhotra6980 2 жыл бұрын
at 0.5 speed it seems like striver is begging in last LOL
@yashgupta-fk3zc
@yashgupta-fk3zc 3 жыл бұрын
aree bhaaiyaa bhaiyaa halke halkee... SLE(SPEED LIMIT EXEDDED) ajaygi barna:xd
@eduflex7931
@eduflex7931 3 жыл бұрын
Too good🤣🤣🤣
@curs3m4rk
@curs3m4rk 3 жыл бұрын
AWESOMMEE !!! LOVED IT
@Learnprogramming-q7f
@Learnprogramming-q7f 8 ай бұрын
Thank you Bhaiya
@om-prakash-yadav
@om-prakash-yadav Жыл бұрын
mujhe laga mera dimag kaam nhi kar paa raha ..fir dekha ..video thoda jyada hi speed hai 😂😂😂😂😂😂😂😂
@fantasyillusion
@fantasyillusion 2 жыл бұрын
for the python code # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: postorder = [] if root==None: return postorder st1,st2=[root],[] while st1: root = st1.pop() st2.append(root) if root.left: st1.append(root.left) if root.right: st1.append(root.right) while st2: postorder.append(st2.pop().val) return postorder
@subhamsingh9553
@subhamsingh9553 2 жыл бұрын
Bro if you return st2[::-1] instead of postorder array(you don't need a third list) you will get the answer second while loop is not necessary
@atharvacodes3705
@atharvacodes3705 3 жыл бұрын
The space complexity should be O(N) right? Even though we're using two stacks, in the end, sum of number of nodes in both the stacks is N, where N in the number of nodes in the tree.
@lakshay6994
@lakshay6994 2 жыл бұрын
yes
@codding32world50
@codding32world50 2 жыл бұрын
yess
@lavanyaprakashjampana933
@lavanyaprakashjampana933 2 жыл бұрын
we love your content and we love you....🖤
@coolgaurav5163
@coolgaurav5163 4 ай бұрын
Understood
@ashitasrivastava681
@ashitasrivastava681 Жыл бұрын
UNDERSTOOD!
@_hulk748
@_hulk748 Жыл бұрын
Understood sir🙏🙇‍♂❤
@dhivyashri6554
@dhivyashri6554 3 жыл бұрын
hello bhaiya! thank you so much for the video, but i think it's sped up could u check that if possible
@AkashKinage-ir9ez
@AkashKinage-ir9ez Жыл бұрын
Thank you stiver for your amazing playlists :)
@RahulKumar-rk1tf
@RahulKumar-rk1tf 2 жыл бұрын
Start at- 00:40
@as_a_tester
@as_a_tester 2 жыл бұрын
tysm striver bhai
@jambajuice07
@jambajuice07 Жыл бұрын
ok will have to cram this method
@runtime379
@runtime379 3 жыл бұрын
awsome series bhaiya
@surabhichoubey2987
@surabhichoubey2987 2 жыл бұрын
Bhiya plz use white pan while explaining
@mohitharpalani6025
@mohitharpalani6025 2 жыл бұрын
understooood
@ayushmansingh2650
@ayushmansingh2650 3 жыл бұрын
please watch it 0.5 of normal speed.
@prantikofficial
@prantikofficial 3 жыл бұрын
so true! 😂😂
@ujjwalsharmaiiitunacse3884
@ujjwalsharmaiiitunacse3884 Жыл бұрын
Danetawasi code :- class Solution{ public: vector postOrder(Node* root) { stack st; stack st1; vector ans; if(root!=NULL) st.push(root); while(!st.empty()) { Node* temp =st.top();st.pop(); if(temp==NULL) { continue; } st1.push(temp->data); Node* left=temp->left; Node* right=temp->right; st.push(left); st.push(right); } while(!st1.empty()) { ans.push_back(st1.top()); st1.pop(); } return ans; } };
@krishnavamsichinnapareddy
@krishnavamsichinnapareddy 2 жыл бұрын
Understood 👍
@saumitrakaushal5369
@saumitrakaushal5369 6 ай бұрын
me watching the whole series at 2x , suddenly this video at 4x :D
@PrakharKulshrestha-q6e
@PrakharKulshrestha-q6e Жыл бұрын
understood
@SURISETTISRIRAMNITAP
@SURISETTISRIRAMNITAP Жыл бұрын
can we use vector in place of second stack as it is just holding the node data, if use the vector we can reverse it at the end!!
@ak67373
@ak67373 Жыл бұрын
If we add in list instead of 2nd stack and then reverse it?
@Student-j4u
@Student-j4u 2 ай бұрын
yeah we can
@deepbytes4854
@deepbytes4854 2 жыл бұрын
# Python code stack1 = [root] # initialise stack with root stack2 = [] while stack1 : node = stack1.pop() # pop from stack1 if node is not None : stack2.append(node.val) # in stack2 append node.val if node.left is not None : stack1.append(node.left) if node.right is not None : stack1.append(node.right) return stack2[::-1] # return stack2 in reverse
@ornatetrout
@ornatetrout Жыл бұрын
How SC is 2N? At any point of time we are going to store a node only once. The node can be present in stack 1 or in stack 2. So, at max sum of size of stack 1 and stack 2 at any point of time can be N. So, SC should be O(N). Striver bro please clarify my doubt.
@reshihashim4094
@reshihashim4094 2 жыл бұрын
1kth like is mine ❤️🔥
@priyaanshusoni
@priyaanshusoni 2 ай бұрын
We can Solve this problem by O(N) also Bhaiya , /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: // void PostOrder(TreeNode* root , vector&ans){ // if(root==nullptr) return ; // PostOrder(root->left,ans); // PostOrder(root->right,ans); // ans.push_back(root->val); // } vector postorderTraversal(TreeNode* root) { // vectorans; // PostOrder(root,ans); // return ans; //post order traversal using one stack stack st; vectorans; if(root==NULL){ return ans; } st.push(root); while(!st.empty()){ TreeNode* temp =st.top(); st.pop(); ans.push_back(temp->val); if(temp->left) st.push(temp->left); if(temp->right) st.push(temp->right); } reverse(ans.begin() , ans.end()); return ans; } }; AND PLEASE PLEASE BRING LATEST TREE & GRAPH SERIES .
@1tav0
@1tav0 2 жыл бұрын
Thank you so much striver for these series. You are a great help to people like me
@altamashsabri8142
@altamashsabri8142 2 жыл бұрын
Understood
@shivangisrivastava1158
@shivangisrivastava1158 3 жыл бұрын
Amazing video!
@rahulsrivastava1040
@rahulsrivastava1040 2 жыл бұрын
U r in final year ?
@abhaymandal4903
@abhaymandal4903 10 ай бұрын
I think tc will be 0(2n)
@tusharrustagi5729
@tusharrustagi5729 2 жыл бұрын
understood
@lone_wolf7721
@lone_wolf7721 3 жыл бұрын
instead of using another stack can't we use vector and reverse it?
@takeUforward
@takeUforward 3 жыл бұрын
Yeah as you wish. Concept stays the same.
@ayushop1921
@ayushop1921 3 жыл бұрын
@@takeUforward so bhaiya in this approach the space complexity will be O(1) na ?\
@shardulwagh904
@shardulwagh904 2 жыл бұрын
@@ayushop1921 In the worst case we add all nodes of the tree to the stack, making it O(n)
@deepakgurjar3746
@deepakgurjar3746 2 жыл бұрын
but for this u heave to take care of node and value...in vector u push data but for check whether left of node or right of node exist there must be a node u are checking not data\value :)
@mixshots1801
@mixshots1801 10 ай бұрын
My solution for iterative post-order traversal and it passed all test cases in leetcode: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector postorderTraversal(TreeNode* root) { vector v; auto node=root; stack st; while(true){ if(node!=NULL){ st.push(node); v.push_back(node->val); node=node->right; } else{ if(st.empty())break; auto temp=st.top(); st.pop(); node=temp->left; } } reverse(v.begin(),v.end()); return v; } }; TC=O(N+N)
@sahilkumarsingh8517
@sahilkumarsingh8517 3 жыл бұрын
Understood😁
@rishabhgupta1222
@rishabhgupta1222 6 ай бұрын
Watch it in 0.6x for a normal person
@utkarshsharma6650
@utkarshsharma6650 2 жыл бұрын
understoooood. thanks :)
Вопрос Ребром - Джиган
43:52
Gazgolder
Рет қаралды 3,8 МЛН
ВЛОГ ДИАНА В ТУРЦИИ
1:31:22
Lady Diana VLOG
Рет қаралды 1,2 МЛН
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 438 М.
L9. Iterative Preorder Traversal in Binary Tree | C++ | Java | Stack
6:50
L10. iterative Inorder Traversal in Binary Tree | C++ | Java | Stack
11:14
Best Books for Learning Data Structures and Algorithms
14:01
Engineering with Utsav
Рет қаралды 374 М.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 673 М.
3 Types of Algorithms Every Programmer Needs to Know
13:12
ForrestKnight
Рет қаралды 499 М.
Вопрос Ребром - Джиган
43:52
Gazgolder
Рет қаралды 3,8 МЛН