L12. Iterative Postorder Traversal using 1 Stack | C++ | Java | Binary Trees

  Рет қаралды 252,189

take U forward

take U forward

Күн бұрын

Пікірлер: 308
@takeUforward
@takeUforward 3 жыл бұрын
This topic is bit tricky, so try to dry run some trees. Its kinda algorithm that you need to remember. Cannot help 😫 Rest all topics are intuitive.. Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79
@sehejwahla5437
@sehejwahla5437 2 жыл бұрын
thanx for this comment.
@worldfromhome4033
@worldfromhome4033 2 жыл бұрын
Thanks for telling because I was worried as it was not intuitive
@traymk
@traymk Жыл бұрын
Thanks for commenting this
@huungryyyy
@huungryyyy 4 ай бұрын
Thnku for thiss😁😁
@mohammedaffann
@mohammedaffann 2 жыл бұрын
one more way of using 1 stack would be, in the previous 2 stack video, instead of using 2nd stack we can push into ans. And in the end, we can reverse ans.
@SadhanaSharma
@SadhanaSharma Жыл бұрын
yesss! thankss
@darkexodus6404
@darkexodus6404 Жыл бұрын
Simply clever.
@amit2194
@amit2194 Жыл бұрын
thanks man
@codewithnoob160
@codewithnoob160 Жыл бұрын
indeed
@divyanshjaiswal6964
@divyanshjaiswal6964 Жыл бұрын
Yes you are absolutely correct but in doing so Your time complexity will increase on the other hand to O(nlogn)
@anmolswarnkar7707
@anmolswarnkar7707 3 жыл бұрын
This just makes you appreciate the "magic" of recursion lol.
@himalayagupta7744
@himalayagupta7744 2 жыл бұрын
++, without recursion we are doomed.
@demonslayer4607
@demonslayer4607 2 жыл бұрын
How?
@himalayagupta7744
@himalayagupta7744 2 жыл бұрын
@@demonslayer4607 first year ???
@himalayagupta7744
@himalayagupta7744 2 жыл бұрын
@@demonslayer4607 recursion is superpower, treat it as one
@demonslayer4607
@demonslayer4607 2 жыл бұрын
@@himalayagupta7744 how bro u r so comfortable with recursion? Please give tips bro
@krishnasudan3410
@krishnasudan3410 2 жыл бұрын
I have thought a better approach with same O(2N) TC and O(N) space. Postorder is : Left Right Root Reverse Postorder is: Root Right Left Try Finding Reverse Postorder like preorder using one stack O(N) time and O(N) space Then reverse the resultant vector, that will be the answer O(N) time Overall O(2N) time and O(N) space Code Below: vector postorderTraversal(TreeNode* root) { vector res; if(!root) return res; stack s; s.push(root); while(!s.empty()){ TreeNode* temp = s.top(); s.pop(); res.push_back(temp->val); if(temp->left) s.push(temp->left); if(temp->right) s.push(temp->right); } reverse(res.begin(),res.end()); return res; } Like if it helped you.
@AnandSharma-lt8wq
@AnandSharma-lt8wq 2 жыл бұрын
// TC: O(2n) AUX: O(H) // little more optimised ArrayList postOrder(Node node) { ArrayDeque st = new ArrayDeque(); ArrayList al = new ArrayList(); Node curr = node; while(curr!=null || !st.isEmpty()){ while(curr!=null){ al.add(curr.data); if(curr.left!=null) st.push(curr.left); curr=curr.right; } curr= st.poll(); } Collections.reverse(al); return al; }
@dhruvbhatnagar4999
@dhruvbhatnagar4999 2 жыл бұрын
Thanks mate!
@adithyab967
@adithyab967 Ай бұрын
Appreciate it
@Dinesh_Dumka
@Dinesh_Dumka 22 күн бұрын
But it will not work always
@turjobennington1677
@turjobennington1677 Жыл бұрын
the best solution I found in LC vector postOrder(Node* node) { vectorans; stackst; st.push({node,false}); while(!st.empty()){ Node*curr=st.top().first; bool isDone=st.top().second; if(isDone){ ans.push_back(curr->data); st.pop(); } else{ st.top().second=true; if(curr->right)st.push({curr->right,false}); if(curr->left)st.push({curr->left,false}); } } return ans; }
@sandeepdas1883
@sandeepdas1883 3 жыл бұрын
Forget about the source codes, these dry runs are so amazing that they have made life so easy for me 😎😋
@rabindrapatra7151
@rabindrapatra7151 Жыл бұрын
use intellij
@niteshkhanna690
@niteshkhanna690 Жыл бұрын
kaha job kar rahe fir abhi ?
@player-te8tf
@player-te8tf 2 жыл бұрын
Kuddos to your hardwork in the recursion videos, the way you used to make function blocks for each recursive calls is what helping me to visualise and grasp the concepts.
@rishabhtiwari7380
@rishabhtiwari7380 Жыл бұрын
it can be also simply done like we did in pre-order , but in this we have to push first left child then right child,also we store values in the final array from end! Thankyou for this wonderful dry run.
@kushalloya4640
@kushalloya4640 8 ай бұрын
can you elaborate this please??
@subhajitdey135
@subhajitdey135 3 ай бұрын
A little note to each bit of code in this traversal : vector postOrder(Node* root) { // Your code here vectorpostorder; if(!root) return postorder; Node* curr=root; stackst; while(!st.empty() || curr){ if(curr){ // if the left exists simply put the left in the stack as in postorder left comes first st.push(curr); curr=curr->left; } else{ Node* temp=st.top()->right; // if temp is null that means the left and right of the st.top() node is already done, time to push it in the vector if(!temp){ temp=st.top(); st.pop(); postorder.push_back(temp->data); // if the current temp is right of st.top() and there is no left present for st.top() (thats why temp==st.top()->right )simply push it in the vector as there is no left present. while(!st.empty() && temp==st.top()->right){ temp=st.top(); st.pop(); postorder.push_back(temp->data); } } // this while loop handles this area : 4 \ 5 \ 6 else curr=temp; } } return postorder; } Hope this could help someone understand better
@AbhishekAnand-vg2tm
@AbhishekAnand-vg2tm Ай бұрын
really helped kudos brother.
@tusharsinghal1333
@tusharsinghal1333 2 жыл бұрын
we can just follow the procedure of 2 stacks but replacing the functionality of the 2nd stack with the container vector itself and then at the end we can reverse the vector before returning it. Not aware if this would have any efficiency tradeoffs but does the job with a single stack.
@ka_ka3141
@ka_ka3141 2 жыл бұрын
absolutely correct
@vivekthakur6686
@vivekthakur6686 2 жыл бұрын
Yes
@kunalgoel9608
@kunalgoel9608 2 жыл бұрын
Yeah Just coded it in java
@harshgupta958
@harshgupta958 2 жыл бұрын
Great but If interviewer asked to print instead of storing in a vector then, this approach will be costly.
@adityaaditya7286
@adityaaditya7286 2 жыл бұрын
Technically that is also a stack.. What if interviewer would say print rather than store in vector
@605_samikrdas4
@605_samikrdas4 2 жыл бұрын
i assure you this is quite a tricky one, but what an explanation man !
@nitingupta1417
@nitingupta1417 3 жыл бұрын
we can do it this way as well: post order is left->right->root; Do traversal in this way--> a kind of preorder root->right->left reverse the result reverseOf(root->right->left) == left->right->root (here you got your postorder) vector postorderTraversal(TreeNode* root) { stacks; if(!root)return {}; s.push(root); vectorv; while(s.size()>0){ TreeNode*node=s.top(); v.push_back(node->val); s.pop(); if(node->left){ s.push(node->left); } if(node->right){ s.push(node->right); } } reverse(v.begin(),v.end()); return v; }
@rahulsaw8838
@rahulsaw8838 3 жыл бұрын
#include using namespace std; class Node { public: int data; Node*left; Node*right; Node(int val) { data = val; left = NULL; right = NULL; } }; Node*buildTree() { int n; cin >> n; if (n == -1) { return NULL; } Node*root = new Node(n); root->left = buildTree(); root->right = buildTree(); return root; } void postOrder(Node*root) { if (!root)return ; postOrder(root->left); postOrder(root->right); cout data left) { continue; } st.push({{st.top().first->left}, {0, 0}}); } else if (!st.top().second.second ) { st.top().second.second = 1; if (!st.top().first->right) { continue; } st.push({{st.top().first->right}, {0, 0}}); } else { cout data
@psibarpsi
@psibarpsi 2 жыл бұрын
Wow! That's a cool idea! I wonder why I couldn't come-up with it. Good job, lad! I wonder, though, if they would like such an approach in an interview.
@chetanraghavv
@chetanraghavv 2 жыл бұрын
Amazing! But I wonder whether this approach will be accepted in interview, because at the end of day, you are traversing the tree in root->right->left fashion, which is not post-order. But still answer is coming correct because we are just printing the reverse of it! Quite clever, if you ask me! 😄
@noone-fl1qb
@noone-fl1qb 5 ай бұрын
Thats the main issue u are using O(nlogn) time for something that can be solved in O(N) time this is correct but definitely not optimal.
@saisardesai5548
@saisardesai5548 4 ай бұрын
@@noone-fl1qb how its O(nlogn) ?
@AdityaKumar-be7hx
@AdityaKumar-be7hx Жыл бұрын
Solution inspired from the 2 stack solution. The second stack is basically used for storing the answer in reverse. We don't really need that. class Solution { public: vector postorderTraversal(TreeNode* root) { vector preorder; stack st; st.push(root); while(!st.empty()){ auto curr = st.top(); st.pop(); // post order = left, right, root // reverse is root, right, left if(curr!=nullptr){ preorder.push_back(curr->val); st.push(curr->left); st.push(curr->right); } } reverse(preorder.begin(), preorder.end()); return preorder; } };
@bhavkushwaha
@bhavkushwaha 7 ай бұрын
Was difficult to follow in one go, but rewatching some portions helped in understanding. Thankyou Striver!
@averylazyandweirdhuman
@averylazyandweirdhuman 5 ай бұрын
Nice Striver! But your graph series feels more interactive because of your gestures and emphasis on important things. Also, the cursor is larger so I could easily see where are you pointing while dry running the code. Above all, Thank you for the series, it takes a lot of time to shoot, edit and handle the job at the same time and with such consistency it's really commendable. And you're really taking us forward and strive for better. 💫
@anupamtiwary4265
@anupamtiwary4265 5 ай бұрын
modifying 2 stack approach . this works too. vector postorderTraversal(TreeNode* root) { vectorpreorder; if(!root) return preorder; stacks1,s2; s1.push(root); while(!s1.empty()){ TreeNode *temp = s1.top(); s1.pop(); preorder.push_back(temp->val); if(temp->left) s1.push(temp->left); if(temp->right) s1.push(temp->right); } reverse(preorder.begin(),preorder.end()); return preorder;
@shubham8941
@shubham8941 11 күн бұрын
vector postOrder(Node* node) { stack st1; st1.push(node); vector ans; if(!node) return ans; while(!st1.empty()){ node=st1.top(); ans.push_back(node->data); st1.pop(); if(node->left) st1.push(node->left); if(node->right) st1.push(node->right); } reverse(begin(ans),end(ans)); return ans; }
@rajkr5446
@rajkr5446 2 ай бұрын
We can use the previous video concept, but instead of the second stack we can use the ans vector itself and when returning just reverse it. vector postorderTraversal(TreeNode* root) { vector ans; if(root == NULL) return ans; stack st; st.push(root); while(!st.empty()) { TreeNode* node = st.top(); st.pop(); ans.push_back(node->val); if(node->left != NULL) st.push(node->left); if(node->right != NULL) st.push(node->right); } reverse(ans.begin(), ans.end()); return ans; }
@SushantKumarGond
@SushantKumarGond 2 ай бұрын
one more way of using 1 stack would be, in the previous 2 stack video, instead of using 2nd stack we can push into ans. And in the end, we can reverse ans. vector postorderTraversal(TreeNode* root) { ios::sync_with_stdio(false); cin.tie(nullptr); vectorans; if(root==NULL) return ans; stackst; st.push(root); while(!st.empty()) { TreeNode* first=st.top(); st.pop(); if(first->left!=NULL) st.push(first->left); if(first->right!=NULL) st.push(first->right); ans.push_back(first->val); } reverse(ans.begin(),ans.end()); return ans; }
@MYANASANTHOSHINI
@MYANASANTHOSHINI 8 ай бұрын
Striver thank you so much without looking at the intuition I was able to crack the logic all because of you thank you so much
@closer9689
@closer9689 5 ай бұрын
My Approach to this Question is very different....I am storing a pair 0f {Node*,StatusValue} in the stack instead of {Node*}, Here statusValue tells whether the the currNode's entire left and right subtree has been visited or not. For this , If statusValue = 0 means neither left nor right subtree is visited till now.If statusValue = 1 , THat means left subtree is visited. If statusValue = 2, means both left and right subtree are visited and now we will add this node->val in the vector the Code is: /** * 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) { if(root == NULL) return {}; stack stk; vector postorder; stk.push({root,0}); while(!stk.empty()) { int status = stk.top().second; TreeNode* curr = stk.top().first; if(status == 2 || (curr->left == NULL && curr->right == NULL)) { postorder.push_back(curr->val); stk.pop(); } else if(status == 1) { stk.top().second++; if(curr->right != NULL) stk.push({curr->right,0}); } else if(status == 0) { stk.top().second++; if(curr->left != NULL) stk.push({curr->left,0}); } } return postorder; } };
@_neha_43
@_neha_43 3 ай бұрын
i could understand this better than what he explained it in the video for some reason, thankyou!!
@closer9689
@closer9689 3 ай бұрын
@@_neha_43 Glad to know😁
@muskankalra2516
@muskankalra2516 3 жыл бұрын
I did a dry run on 3 different examples, it is very clear now :-)
@itz_me_imraan02
@itz_me_imraan02 3 жыл бұрын
Watch it 2-3 times it will be clear 👍
@himanshusharma261
@himanshusharma261 3 жыл бұрын
+1
@devanshuvashishtha6932
@devanshuvashishtha6932 2 жыл бұрын
My Logic based on Pre-Order traversal Pre-order traversal is root-left-right, and post order is left-right-root. Modify the code for pre-order to make it root-right-left, and then reverse the output so that we can get left-right-root . Create an empty stack, Push root node to the stack. Do following while stack is not empty. 1. pop an item from the stack and print it. 2. push the left child of popped item to stack. 3. push the right child of popped item to stack. reverse the ouput.
@rabindrapatra7151
@rabindrapatra7151 Жыл бұрын
you are remembering code or algo. it is not understanding i feel
@HemanthaKumarYadav
@HemanthaKumarYadav 15 күн бұрын
If you find the above algorithm tricky like me, you can follow this which is easy and intuitive to understand: A variation of the two stack approach, but uses Collections.reverse() method instead of using a stack. public List postorderTraversal(TreeNode root) { List result = new ArrayList(); if (root == null) return result; Stack stack = new Stack(); stack.push(root); // The idea is to do (root -> right -> left) and then reverse // to get (left -> right -> root) while (!stack.isEmpty()) { TreeNode current = stack.pop(); result.add(current.val); // Push left first so that it's processed after right if (current.left != null) { stack.push(current.left); } if (current.right != null) { stack.push(current.right); } } // Reverse the result to get postorder Collections.reverse(result); return result; }
@AbhishekThakur-vr4zy
@AbhishekThakur-vr4zy 2 жыл бұрын
Hii bhai , your videos are amazing , also in this question no need to use this complex code , it can simply be done like preorder vector postorderTraversal(TreeNode* root) { vector postorder; if(root==NULL) return postorder; stack st; st.push(root); while(!st.empty()) { root=st.top(); st.pop(); postorder.push_back(root->val); if(root->left!=NULL) st.push(root->left); if(root->right!=NULL) st.push(root->right); } reverse(postorder.begin(), postorder.end()); return postorder; }
@niteshshandilya4226
@niteshshandilya4226 2 жыл бұрын
thnx bro
@divyareddy7622
@divyareddy7622 2 ай бұрын
thank you 🎉
@sayantangupta6211
@sayantangupta6211 3 жыл бұрын
One easy approach can be : Take 1 stack and 1 vector. Initially push root in stack. Then , while stack is not empty, push back the top in vector, pop the top from stack and then push left child 1st and then right child. Finally after stack is empty, reverse the vector. Final postorder traversal will be in the vector //Code: vector postorderTraversal(TreeNode* root) { vectorans; if(root == NULL) return ans; stacks; s.push(root); while(!s.empty()) { TreeNode *p = s.top(); ans.push_back(p->val); s.pop(); if(p->left) s.push(p->left); if(p->right) s.push(p->right); } reverse(ans.begin(), ans.end()); return ans; }
@PrinceKumar-el7ob
@PrinceKumar-el7ob 3 жыл бұрын
isn't it what we have done earlier using two stacks !!
@sunilgrover4178
@sunilgrover4178 3 жыл бұрын
In that case, you will be implementing stack functionality using vectors. It means, overall, you will be using stack.
@shashankojha3452
@shashankojha3452 3 жыл бұрын
Yup. I also came up with this solution. This could have worked as as replacement for single stack method if that extra reverse step at last was not there. Because the space complexity would be O(n) only if we use 1 stack and 1 vector (because we don't generally consider the space used in returning the answer). But since we are reversing the vector in the end , it will add to our time complexity.
@krishnarajs929
@krishnarajs929 2 жыл бұрын
@@shashankojha3452time complexity will be O(N)+O(N) but in general , the time complexity is O(N) only
@matrixtoogood5601
@matrixtoogood5601 2 жыл бұрын
This will be slightly slower than 2 stacks because dynamic array requires doubling of space at times (so insertion can be O(N) in worst case at times) whereas stack is a linked list so insertion is always O(1). Although, in average case both are same
@akhilesh59
@akhilesh59 3 жыл бұрын
This was a bit complex, and I had to watch this thrice to understand the concept. It'll be easy to understand if we try to implement the logic on paper. Thank you bhaiya for the explanation!
@takeUforward
@takeUforward 3 жыл бұрын
Yes i have written on pinned comment, that self doing will make this question clear..
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
@@takeUforward that's what i understood , STACK :-> represent those guys or nodes whose left traversal is totaly complete TEMP: -> remove temp , and replace it with two variables instead 1.) isRightViisted , 2.) nodeThatCompletedTraversal ( both left and right ). vector postOrder(Node* root) { if(root==nullptr) return {}; vector postOrder; stack leftExploredGuys; // stack will only store those guys whose left side is explored Node * node = root; while(node!=nullptr or !leftExploredGuys.empty()){ if(node!=nullptr){ // means this node's left is not explored leftExploredGuys.push(node); // explore left node = node->left; }else{ // if node == nullptr , means left is totaly explored // let's see if the right is explored or not bool isRightExplored = (leftExploredGuys.top()->right == nullptr); if(isRightExplored){ // means this node's overall traversal is over , means this node is of no use Node * nodeThatCompletedTraversal = leftExploredGuys.top(); leftExploredGuys.pop(); postOrder.push_back(nodeThatCompletedTraversal->data); // now stack might contains more nodes whose traversal is completed while(!leftExploredGuys.empty() and leftExploredGuys.top()->right == nodeThatCompletedTraversal){ // if a node's right is a guy who is completly traversed // and it was present in a stack whose left is completly explore // means this node's traversal is also completed nodeThatCompletedTraversal = leftExploredGuys.top(); leftExploredGuys.pop(); postOrder.push_back(nodeThatCompletedTraversal->data); } }else{ // explore the right guy node = leftExploredGuys.top()->right; } } } return postOrder; }
@manavbansal3953
@manavbansal3953 Жыл бұрын
@@pulkitjain5159 very good explanation. The dry run was difficult to understand, you explained the reason for every line of code. Thank you.
@manavbansal3953
@manavbansal3953 Жыл бұрын
@@pulkitjain5159 could you please explain the other iterative methods of traversal in a similar way please
@shubhamkumarsingh8818
@shubhamkumarsingh8818 6 ай бұрын
this is the more easier appraoch vector postorderTraversal(TreeNode* root) { vector ans; stack st; if(root == NULL) { return ans; } st.push(root); while(!st.empty()) { TreeNode* node = st.top(); st.pop(); ans.insert(ans.begin(), node->val); if(node->left) { st.push(node->left); } if(node->right) { st.push(node->right); } } return ans; }
@codewithme05
@codewithme05 4 ай бұрын
but this takes time complexity of O(n^2) instead you can just push_back into the ans array and later can reverse it. This reduces to O(n). But it's definetly a good thought
@lifehustlers164
@lifehustlers164 Жыл бұрын
Completed 13/54(24% done) !!!
@sauravchandra10
@sauravchandra10 Жыл бұрын
Even though I have tried hard, I can't wrap my head around this algorithm. I dont want to memorise this and so I think I am going to skip it. A better approach would be to make slight modifications in the previous approach and instead of using a second stack, I can store the answer in a vector and reverse it before returning it.
@thomasgeorge4578
@thomasgeorge4578 3 жыл бұрын
This video is just 🔥🔥, Your dry run is all that was required !!! Amazing!!!
@staywithmeforever
@staywithmeforever 8 ай бұрын
didnt understand a single bit didnt explain why that code works even thought u liked it?
@rabindrapatra7151
@rabindrapatra7151 7 ай бұрын
@@staywithmeforever he explained on the start , left, right then again keep going left, in between maintain in stack
@mahmudaliza4079
@mahmudaliza4079 Ай бұрын
After watching this video, I felt like there is hope in life :)
@adityapandey23
@adityapandey23 2 ай бұрын
Understood Did some dry runs and it was easy and intuitive
@willturner3440
@willturner3440 3 жыл бұрын
This 12 min video took 2 hrs to understand, 😁
@BRSanush
@BRSanush 2 жыл бұрын
Same here
@rabindrapatra7151
@rabindrapatra7151 Жыл бұрын
@@BRSanush because video is focussed on code
@abhishekjhanji3014
@abhishekjhanji3014 Жыл бұрын
Another 1 stack approach for this problem vector postorderTraversal(TreeNode* root) { vectorv; if(root==NULL) return v; stack st; st.push(root); while(!st.empty()){ TreeNode*node=st.top(); st.pop(); v.push_back(node->val); if(node->left!=NULL) st.push(node->left); if(node->right!=NULL) st.push(node->right); } reverse(v.begin(),v.end()); return v; }
@stith_pragya
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video......🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@gourabmukherjee4848
@gourabmukherjee4848 Жыл бұрын
Very Good Explanation!! I've followed another approach to solve using 1 stack only, the code is mentioned below Stackstack=new Stack(); LinkedListans=new LinkedList(); if(root!=null){ stack.push(root); while(!stack.isEmpty()){ TreeNode ptr=stack.pop(); if(ptr.left!=null) stack.push(ptr.left); if(ptr.right!=null) stack.push(ptr.right); ans.addFirst(ptr.val); } } return ans;
@gautamjangir8927
@gautamjangir8927 2 жыл бұрын
The BEST explanation in the entire youtube....Thanks
@rishabhkumar8115
@rishabhkumar8115 3 жыл бұрын
Forget about the source codes, these dry runs are so amazing that they have made life so easy for me
@piyushacharya7696
@piyushacharya7696 2 жыл бұрын
reach++. If you're having trouble understanding it, go back to the previous video and instead of using another stack, just reverse the array. It makes no sense to waste a few hours. The complexity of space and time remains unchanged, and it is also more intuitive.
@harshitsen5479
@harshitsen5479 8 ай бұрын
This can be done as preorder as well, just make sure the we are using LinkedList as an implementing class for List, and instead of doing "add" operation, perform "addFirst" operation. while(!mainStack.isEmpty()) { TreeNode temp = mainStack.pop(); res.addFirst(temp.val); if(temp.left != null) mainStack.push(temp.left); if(temp.right != null) mainStack.push(temp.right); }
@aravintht.k9276
@aravintht.k9276 7 ай бұрын
We can actually use single stack and write similar code like preorder with a simple tweak over it. just traverse left and right instead of right and left. We need to reverse the list at the end. public List postorderTraversal(TreeNode root) { List result = new ArrayList(); Stack stack = new Stack(); if(root == null) return result; stack.push(root); while(!stack.isEmpty()){ root = stack.pop(); result.add(root.val); if(root.left != null) stack.push(root.left); if(root.right != null) stack.push(root.right); } Collections.reverse(result); return result; }
@pragatiagrawal201
@pragatiagrawal201 2 жыл бұрын
Finally, after seeing this video my brain is at peace!! Thanks a lot for this😌😌
@lonewolf-_-8634
@lonewolf-_-8634 Жыл бұрын
The moment you understand the feasibility provided by Recursion ^-^...
@kumarsundaram6762
@kumarsundaram6762 Жыл бұрын
LeetCode solution using 1 stack and a map (visited array ):- class Solution { public: vector postorderTraversal(TreeNode* root) { if(root==NULL) return {}; stack stk; stk.push(root); map vis; vector ans; while(stk.size()>0) { TreeNode* node=stk.top(); stk.pop(); if(vis[node]==0) { vis[node]=1; stk.push(node); if(node->right) stk.push(node->right); if(node->left) stk.push(node->left); } else { ans.push_back(node->val); } } return ans; } };
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
you used a graph's dfs approach , treated a tree as a graph , but it tooked some what O(N) exptra space , nice brute force approach
@nileshsinha7869
@nileshsinha7869 3 жыл бұрын
Great explanation man. The dry run really helped to understand. Keep up the good work❤🙌
@prabhakaran5542
@prabhakaran5542 4 ай бұрын
Understood ❤❤❤
@theSeniorSDE
@theSeniorSDE 3 жыл бұрын
Finally understood this problem well and took notes.
@amborishnath7755
@amborishnath7755 2 жыл бұрын
can you write down the steps here?
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
@@amborishnath7755 0 seconds ago THOSE GUYS WHO DID'NT UNDERSTAND , THE DRY RUN , HERE IS SOMETHING TO HELP YOU :) STACK :-> represent those guys or nodes whose left traversal is totaly complete TEMP: -> remove temp , and replace it with two variables instead 1.) isRightViisted , 2.) nodeThatCompletedTraversal ( both left and right ). JUST THIS CODE WITH COMMENTS , YOU WILL UNDERSTAND. vector postOrder(Node* root) { if(root==nullptr) return {}; vector postOrder; stack leftExploredGuys; // stack will only store those guys whose left side is explored Node * node = root; while(node!=nullptr or !leftExploredGuys.empty()){ if(node!=nullptr){ // means this node's left is not explored leftExploredGuys.push(node); // explore left node = node->left; }else{ // if node == nullptr , means left is totaly explored // let's see if the right is explored or not bool isRightExplored = (leftExploredGuys.top()->right == nullptr); if(isRightExplored){ // means this node's overall traversal is over , means this node is of no use Node * nodeThatCompletedTraversal = leftExploredGuys.top(); leftExploredGuys.pop(); postOrder.push_back(nodeThatCompletedTraversal->data); // now stack might contains more nodes whose traversal is completed while(!leftExploredGuys.empty() and leftExploredGuys.top()->right == nodeThatCompletedTraversal){ // if a node's right is a guy who is completly traversed // and it was present in a stack whose left is completly explore // means this node's traversal is also completed nodeThatCompletedTraversal = leftExploredGuys.top(); leftExploredGuys.pop(); postOrder.push_back(nodeThatCompletedTraversal->data); } }else{ // explore the right guy node = leftExploredGuys.top()->right; } } } return postOrder; } JINKO POSTORDER ITERATIVE SAMAJH NAHI AYA EK BAAR READ KARLENA CODE
@divycodes
@divycodes 5 ай бұрын
@@pulkitjain5159 ty, this helped
@indranilthakur3605
@indranilthakur3605 2 жыл бұрын
Java solution with one stack - public List postorderTraversal(TreeNode root) { List res = new ArrayList(); if(root == null) return res; Stack s = new Stack(); s.push(root); while(!s.isEmpty()){ root = s.pop(); res.add(0, root.val); if(root.left != null) s.push(root.left); if(root.right != null) s.push(root.right); } return res; }
@nawabkhan4916
@nawabkhan4916 2 жыл бұрын
great work, and have lots of sponsor ad so that you can provide great videos.
@coding8000
@coding8000 Жыл бұрын
Again @takeUforwad, just letting you know, again that's stuff you have done, is GOD's own work, thank you for from bottom of my heart, thanks !!!
@starr_lord0
@starr_lord0 Жыл бұрын
Just a small changes in your previous code(inpired from you). vector postOrder(Node* root) { // Your code here vector res; stack st1; st1.push(root); while(!st1.empty()){ root=st1.top(); st1.pop(); res.push_back(root->data); if(root->left!=NULL) st1.push(root->left); if(root->right!=NULL) st1.push(root->right); } reverse(res.begin(),res.end()); return res; } Simple!!!
@cinime
@cinime 2 жыл бұрын
Understood! So awesome explanation as always, thank you very much!!
@abhaykumarsingh3266
@abhaykumarsingh3266 3 ай бұрын
Don't go with striver's appoarch(its is very tricky) just use 1 stack with previous video approach List ans=new ArrayList(); if(root==null){ return ans; } Stack st1=new Stack(); st1.push(root); while(!st1.isEmpty()){ TreeNode temp=st1.pop(); ans.add(0,temp.val); if(temp.left != null){ st1.push(temp.left); } if(temp.right != null){ st1.push(temp.right); } }
@imKushGupta
@imKushGupta Ай бұрын
ans.add(0, temp.val); operation across all nodes becomes O(N^2) in total. The operation ans.add(0, temp.val); takes O(N) time for each insertion because it requires shifting elements to the right.
@imKushGupta
@imKushGupta Ай бұрын
This is right code bro..... TC- O(2N) SC- O(N) List ans = new ArrayList(); if (root == null) { return ans; } Stack st1 = new Stack(); st1.push(root); while (!st1.isEmpty()) { TreeNode temp = st1.pop(); ans.add(temp.val); // Add to the end of the list if (temp.right != null) { st1.push(temp.right); } if (temp.left != null) { st1.push(temp.left); } } // Reverse the list at the end Collections.reverse(ans); return ans;
@rabindrapatra7151
@rabindrapatra7151 7 ай бұрын
video starts at 0:42
@arunachalamm3399
@arunachalamm3399 2 жыл бұрын
Amazing series bhai, from 1:28 in 1.5 x was funny lol😂😂
@anandtripathi
@anandtripathi 2 жыл бұрын
Here is simpler code using logic of iterative preorder. vector postorderTraversal(TreeNode* root) { vector ans; if(root==NULL) return ans; stack st; st.push(root); while(!st.empty()) { auto node = st.top(); st.pop(); ans.push_back(node->val); if(node->left) st.push(node->left); if(node->right) st.push(node->right); } reverse(ans.begin(),ans.end()); return ans; }
@samuelfrank1369
@samuelfrank1369 Жыл бұрын
UNDERSTOOD. THANKS A LOT.
@shivangisrivastava1158
@shivangisrivastava1158 3 жыл бұрын
Finally after 1-2 dry runs, clearly understood. This one is really bit complex.
@SHASHANKRUSTAGII
@SHASHANKRUSTAGII 2 жыл бұрын
indeed
@maazulhaque7293
@maazulhaque7293 2 жыл бұрын
Great Explanation, such a tough topic and how easily you explained... Hats of you man
@amandeep0148
@amandeep0148 3 жыл бұрын
Bhaiya you really taking us forward. Thank you.
@ruchighodasara1644
@ruchighodasara1644 2 жыл бұрын
Dry run is very helpful.
@baibhavsingh9225
@baibhavsingh9225 2 жыл бұрын
i have done it this way. its a bit simpler i think vector ans; stack st; st.push(root); if(root==NULL){return ans;} while(!st.empty()) { TreeNode* cur=st.top();ans.push_back(cur->val);st.pop(); if(cur->left!=NULL){st.push(cur->left);} if(cur->right!=NULL){st.push(cur->right);} } reverse(ans.begin(),ans.end()); return ans;
@shrishtikumari4324
@shrishtikumari4324 2 жыл бұрын
Yeah. Much easier solution. Thanks a lot!!!
@Rajesh-op8zx
@Rajesh-op8zx 2 жыл бұрын
Space complexity will be O(H) and H here is the height of tree , stack can have at max H elements only at one time so S.C is not O(N) here .
@harshitsangwan890
@harshitsangwan890 2 жыл бұрын
Yes, you are correct.
@jasonbrody4618
@jasonbrody4618 3 жыл бұрын
Liked. Cfbr will watch after some time
@trashcan-md7cw
@trashcan-md7cw Ай бұрын
The intuition of this problem is not understandable in 1 watch. But rewatching it and testing on some trees will make it clear... But yeah this is tough...
@amitsinghrana6619
@amitsinghrana6619 2 жыл бұрын
Had to brain-storm for *6 hours* before understanding the part { while(!st.empty() || st.top()->right) } It's basically checking if this node was right child of some other node, if it was then we have visited both childs of that node, so print it and remove it from stack. *temp* stores right child when going down the tree, and contains recently printed node when going up the tree.
@huungryyyy
@huungryyyy 4 ай бұрын
when i saw the questions i did the 2 stack approach of the previous video but instead of taking 2nd stack directly store the answer into result vector and and just reverse the result vector.
@ManishKumar-ml8wz
@ManishKumar-ml8wz Ай бұрын
But for reversing you end up taking O(n) extra time
@vakhariyajay2224
@vakhariyajay2224 Жыл бұрын
Thank you very much. You are a genius.
@bhagyasingh3076
@bhagyasingh3076 3 жыл бұрын
Just do a reverse preOrder and reverse the final vector vector postorderTraversal(TreeNode* root) { vectorpostOrder; if(!root)return postOrder; TreeNode *node = root; stackst; st.push(node); while(!st.empty()) { node = st.top(); st.pop(); postOrder.push_back(node->val); if(node->left)st.push(node->left); if(node->right)st.push(node->right); } reverse(postOrder.begin(),postOrder.end()); return postOrder; }
@bharathkumar5870
@bharathkumar5870 3 жыл бұрын
it is not reverse pre order..it is root---right--left order
@SHASHANKRUSTAGII
@SHASHANKRUSTAGII 2 жыл бұрын
wow man, and yes bharat is right
@SK-cm1hn
@SK-cm1hn 2 жыл бұрын
Then the Solution is in O(N Log N) , this solution is in O(N).
@VAISHNAVIP-z6j
@VAISHNAVIP-z6j 8 ай бұрын
Superb sir❤
@mriduljain1981
@mriduljain1981 Жыл бұрын
completed lecture 12 of Tree playlist with some difficulty and by watching it twice and dry running it on own xD..
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@areebahmadsiddiqui2648
@areebahmadsiddiqui2648 3 жыл бұрын
I want DP series as well
@vipulchoudhary2419
@vipulchoudhary2419 2 жыл бұрын
This is also using 1 stack. // TC --> O(N)[Tree traversal] + O(N)[Reversing the array] // SC --> O(N) class Tree { //Function to return a list containing the postorder traversal of the tree. ArrayList postOrder(Node root) { ArrayList postOrder = new ArrayList(); if(root == null) return postOrder; Stack st1 = new Stack(); st1.push(root); while(!st1.isEmpty()) { Node node = st1.pop(); postOrder.add(node.data); if(node.left != null) st1.push(node.left); if(node.right != null) st1.push(node.right); } Collections.reverse(postOrder); // TC --> O(N) return postOrder; } }
@adityaaditya7286
@adityaaditya7286 2 жыл бұрын
We use second stack basically to reverse the result which u are doing by reversing the array. These are same things. What if i say you to don't store anything and print directly?
@rajeshbora2013
@rajeshbora2013 3 жыл бұрын
Great explanation bro 👏👏👏
@theSeniorSDE
@theSeniorSDE 3 жыл бұрын
Lots of curr and push & push curr in this problem 😂 definitely i will have to watch it once again to understand the algorithm better.
@takeUforward
@takeUforward 3 жыл бұрын
Yeah, its slightly tricky, i will highly recommend to do it by yourself on pen and paper.. to understand it better.
@theSeniorSDE
@theSeniorSDE 3 жыл бұрын
@@takeUforward Took a break for 2 day and revised all the previous topics that i learnt from the previous videos. Now starting again from where I left. 😎
@Kpriyasing
@Kpriyasing 3 жыл бұрын
Amazing content!!
@parthsalat
@parthsalat 2 жыл бұрын
Understood!
@Yash_Parashar
@Yash_Parashar 3 жыл бұрын
In first condition there should be AND not OR , if I am wrong correct me.
@rohandeshmukh3989
@rohandeshmukh3989 3 жыл бұрын
Yeah actually that why it is going in the else part where curr is not null otherwise how will it go in that section
@project_eth
@project_eth 4 ай бұрын
understood, day 3
@DeadPoolx1712
@DeadPoolx1712 Ай бұрын
UNDERSTOOD;
@SHASHANKRUSTAGII
@SHASHANKRUSTAGII 2 жыл бұрын
If we know Iterative post order with 2 stacks, is it required to do with one stack? I mean the time complexity is still same? still the interviewer can ask na? do with one stack?
@_hulk748
@_hulk748 Жыл бұрын
Understood sir❤🙇‍♂🙏
@divyaagarwal3091
@divyaagarwal3091 11 ай бұрын
Thankyou so much sir!
@Learnprogramming-q7f
@Learnprogramming-q7f 8 ай бұрын
Thank you Bhaiya
@studynewthings1727
@studynewthings1727 7 ай бұрын
Understood.
@as_a_tester
@as_a_tester 2 жыл бұрын
tysm striver bhai
@divyaagarwal3091
@divyaagarwal3091 11 ай бұрын
Understood!
@JohnWick-kh7ow
@JohnWick-kh7ow 3 жыл бұрын
Your videos are amazing. Just one suggestion: You could have given this more time. We would understand it better.
@Joy-x9m
@Joy-x9m 2 жыл бұрын
For this video, it was difficult for me to follow the small red dot. I bit more visible would have been nice.
@creativeprojects217
@creativeprojects217 9 ай бұрын
thank you sir♥
@eklavyaprasad5009
@eklavyaprasad5009 3 жыл бұрын
Thanks bhaiya
@heavenlyway5824
@heavenlyway5824 2 жыл бұрын
Hi Raj, I really like all your videos. However missing point is can tell me some 2 minutes, how you come to particular logic, what are your thought process and intuition beyond approach. it will be extremely helpful. For example: in previous video, you said take 2 stacks , 1st insert root to stack1, then take top element of stack1 to stack2, then find left and right of top of top element in stack2, then repeat the same to get the answer. -> I want to know how you come up with this logic? can you take 2 minutes to explain your thought process in this.
@sachinpathak3084
@sachinpathak3084 2 жыл бұрын
there are few questions which required intuition and few question which needs to memorisation
@shreyshah4220
@shreyshah4220 Жыл бұрын
No
@RahulKumar-rk1tf
@RahulKumar-rk1tf 2 жыл бұрын
Start- 00:40
@Dineshsharma-ec6ys
@Dineshsharma-ec6ys 3 жыл бұрын
I have problem. I just watch your video understand the approach and able to code and solve the problem .but after a week i find myself not unable to solve the same problem . so I have to go through the video again.
@sauravpandey3802
@sauravpandey3802 3 жыл бұрын
did you find any solution ??
@lakshsinghania
@lakshsinghania Жыл бұрын
obvio. revision is must studying for one time doesnt make u remember all the things
@krishnavamsichinnapareddy
@krishnavamsichinnapareddy 2 жыл бұрын
Understood 👍
@ordinaryhomosapien1181
@ordinaryhomosapien1181 3 жыл бұрын
This explanation is great 👍
@manaslahon1031
@manaslahon1031 Ай бұрын
if 6 has already been removed from the stack how is it accessible to compare with the st.top()->right? Timestamp- 6:42
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 88 МЛН
When Cucumbers Meet PVC Pipe The Results Are Wild! 🤭
00:44
Crafty Buddy
Рет қаралды 57 МЛН
L21. Vertical Order Traversal of Binary Tree | C++ | Java
18:53
take U forward
Рет қаралды 335 М.
The Last Algorithms Course You'll Need by ThePrimeagen | Preview
16:44
Frontend Masters
Рет қаралды 325 М.
L10. iterative Inorder Traversal in Binary Tree | C++ | Java | Stack
11:14
L9. Iterative Preorder Traversal in Binary Tree | C++ | Java | Stack
6:50
L14. Maximum Depth in Binary Tree | Height of Binary Tree | C++ | Java
8:05
Iterative Postorder traversal of binary tree using one stack
14:05
Tushar Roy - Coding Made Simple
Рет қаралды 116 М.
L36. Serialize and De-serialize Binary Tree | C++ | Java
17:18
take U forward
Рет қаралды 150 М.