Iterative Postorder traversal of binary tree using one stack

  Рет қаралды 116,710

Tushar Roy - Coding Made Simple

Tushar Roy - Coding Made Simple

Күн бұрын

Пікірлер: 93
@uditgaba1450
@uditgaba1450 4 жыл бұрын
Thanks for the explanation! You are saving a lot of time for me. Instead of reading articles or reading codes sometimes , i can simply watch your video . I implemented the code on my own after this video . Code (Java):- public static void postOrderUsingSingleStack(TreeNode root) { Stack s = new Stack(); TreeNode curr = root; while(curr != null || !s.isEmpty()) { while(curr != null) { s.push(curr); curr = curr.left; } if(!s.isEmpty()) { //check is stack top has right child if(s.peek().right != null) { curr = s.peek().right; } else { TreeNode temp = s.pop(); System.out.print(temp.data+" "); while(s.size() > 0 && s.peek().right == temp) { temp = s.pop(); System.out.print(temp.data+" "); } } } }
@santhosh087
@santhosh087 4 жыл бұрын
I almost got the logic while thinking of the problem. I couldn't think of that inner while loop to break the loop when we are done with all the lefts. Though I could understand your initial explanation, its little tough to match the same with the code. Thanks for the great explanation!!.
@kiratsaluja3522
@kiratsaluja3522 3 жыл бұрын
almost got the logic and was stuck at how to check if right is already visited or not. This explains it bang on. Thank u
@meghnasrivastava568
@meghnasrivastava568 5 ай бұрын
Best explanation,I have watched so far!
@ghostpieces2362
@ghostpieces2362 4 жыл бұрын
Tushar, this was an amazing visual walkthrough followed by a brilliant code walkthrough. Thanks for taking the time to share :)
@vvwu7194
@vvwu7194 7 жыл бұрын
Thank you, better than the other explanations I have watched or read.
@mingxiao1939
@mingxiao1939 3 жыл бұрын
Clear and intuitive explanation! Thank you Tushar.
@shreyasingh-sn4bs
@shreyasingh-sn4bs 7 жыл бұрын
Thank you for making learning so much easier :)
@sameer_sah
@sameer_sah 4 жыл бұрын
Great walkthrough. Only thing I want to point out is offer and poll are methods of queue API. We should be using push and pop of stack API.
@yelururao1
@yelururao1 7 жыл бұрын
super explanation..thanks for it..please do more videos on BST , AVL and red-black tree
@abhay7130
@abhay7130 3 жыл бұрын
bolne ke style sun ke gariyane ka hi man karta hai iske. baki sb badiya hai
@sureshiva4605
@sureshiva4605 Жыл бұрын
straigh forward way ....nice....instead of using previous variable or skip counts....this looks clean
@U2011-n7w
@U2011-n7w Жыл бұрын
nice explanation
@shivamdixit8796
@shivamdixit8796 8 жыл бұрын
exceptional explanation.... The algo explanation was so good, that i could code it just by looking halfway through the explanation.....hats off to the amazing work :)
@abhinav4279_
@abhinav4279_ 3 жыл бұрын
This iterative traversal has been messing up my mind for long, not anymore.👍
@JangBahadur3028
@JangBahadur3028 8 жыл бұрын
Awsome tutorial. well explained. Helped me a lot . Thank you Tushar.
@chenboxie6623
@chenboxie6623 8 жыл бұрын
Thank you Tushar, very clear. Understand better now.
@mahee96
@mahee96 3 жыл бұрын
The only thing I was missing, was how to preserve the root which is usually popped off when doing in-order/pre-order iterative traversals, but the important note here is that, we don't pop off the root unless we see that curr.right is null and curr node is right child(KEY POINT) of latest(last) stack entry which means last entry is root, hence know we are done and pop off this right child backtrack to root. So until then root is preserved!! class stack(list): def push(self, val): self.append(val) def peek(self): return self[-1] def LRN(root): st = stack() while root or st: while root: st.push(root) root = root.left root = st.peek().right if root: continue # pop off backstack - backtracking # left node pop off x = st.pop() print(x.val, end=", ") # right, root node pop off while(st and st.peek().right == x): x = st.pop() print(x.val, end=", ") print()
@MrRanjeetaize
@MrRanjeetaize 7 жыл бұрын
Nice explanation.. too much helping
@MithleshKumar-iz1dz
@MithleshKumar-iz1dz 5 жыл бұрын
You are saviour Tushar. Thanks alot!
@utkarshdwivedi586
@utkarshdwivedi586 Жыл бұрын
A quick question :: you used or in the while condition instead of using and so, whenever the curr will be null the loop will break , without giving the correct output. This thing kind of contradicts with your algorithm.
@TwinbeeUK
@TwinbeeUK 2 жыл бұрын
Possibly the clearest iterative postorder traversal of trees shown on KZbin! Will this technique of using one stack work if there are 3 or more child nodes for each parent, or would a two-stack solution be needed then?
@student_03
@student_03 Жыл бұрын
thanks a lot sir amazing explanation
@adityakrishna11
@adityakrishna11 4 жыл бұрын
This just feels like a walkthrough. You know what's happening and how is it happening but you really don't know the why of it? I came up with this implementation which I feel like is closest to what you've explained. void recursivePostOrderTraversal(BinaryTreeNode *root) { if (root) { recursivePostOrderTraversal(root->left); recursivePostOrderTraversal(root->right); cout data left; } else { BinaryTreeNode *current = content.top(); if (current->right != NULL) { root = current->right; } else { content.pop(); cout data right) { current = content.top(); content.pop(); cout data right) { if (content.top()->right != NULL) root = content.top()->right; } } } } while (content.empty() == false); }
@saisusritha
@saisusritha 2 жыл бұрын
Great Explanation
@SonGoku-ep4wj
@SonGoku-ep4wj 5 жыл бұрын
dude you're a legend . thank you !
@jbs2491
@jbs2491 2 жыл бұрын
Thank you this was very helpful. Given that space and time complexity are the same using a single stack vs two stacks (please, correct me if I'm wrong), are there any advantages/disadvantages for using a single stack vs two stacks?
@mprasanth18
@mprasanth18 Жыл бұрын
Thanks a lot. This is very helpfull.
@adhishmalviya2408
@adhishmalviya2408 4 жыл бұрын
this guy reminds me of song..**ek tu hi yaar mera mujhe kya duniya se lena**
@nking99t
@nking99t 5 жыл бұрын
Can you do it without addFirst() or reverse()? otherwise which would just be another preorder traversal.
@ramakrishnaloka7946
@ramakrishnaloka7946 4 жыл бұрын
Is code handling the scenario of checking last popped element is equal to temp.right ???????
@karthickm9846
@karthickm9846 6 жыл бұрын
Great Video Tushar. In your code, you used, Stack stack = new LinkedList().. Is this correct?
@vinutd210
@vinutd210 5 жыл бұрын
Good catch. I believe it is a typo. it should be Stack stack = new Stack();
@vinutd210
@vinutd210 5 жыл бұрын
Tushar has used Deque in most of his code that he has referenced in the description. Hence, there are things like, "offer", "poll" in his code on the whiteboard. Here is a proper stack version of this function. public static void postOrderItrOneStack(TreeNode root){ TreeNode current = root; Stack stack = new Stack(); while(current != null || !stack.isEmpty()){ if(current != null){ stack.push(current); current = current.left; }else{ TreeNode temp = stack.peek().right; if (temp == null) { temp = stack.pop(); System.out.print(temp.val + " "); while (!stack.isEmpty() && temp == stack.peek().right) { temp = stack.pop(); System.out.print(temp.val + " "); } } else { current = temp; } } } }
@falakk22
@falakk22 7 жыл бұрын
Superb Explanation Thanks!
@paraskamboj1039
@paraskamboj1039 5 ай бұрын
Thankyou so much sir
@sknayak3246
@sknayak3246 5 жыл бұрын
I believe, it won't work if both left and right child have same values. Kindly LMK if I am missing something here.
@shnerdz
@shnerdz 5 жыл бұрын
we compare referenced to node, not the values of the nodes, otherwise youd be correct
@vinayak186f3
@vinayak186f3 3 жыл бұрын
20 baar padhke bhool chuka hu , ek baar aur sahi 🙂
@KeshariPiyush24
@KeshariPiyush24 3 жыл бұрын
hota hai mere saath bhi hota hai.....kya kar sakte haiXD
@ragingpahadi
@ragingpahadi 3 жыл бұрын
Simple and easy to understand ! public List postorderTraversal(TreeNode root) { List res = new ArrayList(); Stack stack = new Stack(); TreeNode lastNodeVisited = null; TreeNode curr = root; while(!stack.isEmpty() || curr != null) { if(curr != null) { stack.push(curr); curr = curr.left; } else { TreeNode x = stack.peek(); if(x.right != null && x.right != lastNodeVisited) { curr = x.right; } else { res.add(x.val); stack.pop(); lastNodeVisited = x; } } } return res; }
@prakashkrishna2566
@prakashkrishna2566 2 жыл бұрын
whatis the use of the variable lastNodeVisited?
@avranj
@avranj 2 жыл бұрын
Where is this youtuber now?
@sanketkalokhe7400
@sanketkalokhe7400 8 ай бұрын
why we need to check if the popped node is right or not I couldn't understand that part if anyone knows the solution please let me know
@karanb2067
@karanb2067 4 жыл бұрын
explanation is great but algorithm implementation is a real head scratcher....you gotta mug it up for the most part.
@veronicadey6731
@veronicadey6731 2 жыл бұрын
So tough 🤯🤯🤯
@saksham9170
@saksham9170 4 жыл бұрын
Rote memorization at it's peak
@charan_75
@charan_75 3 жыл бұрын
They are standard algorithms. How else would you explain genius?
@DharminMajmudar
@DharminMajmudar 6 жыл бұрын
Great explanation!
@musheerahmed5815
@musheerahmed5815 8 жыл бұрын
Brilliant. Thanks!!
@aman0509
@aman0509 3 жыл бұрын
Thanks for simplifying the things. Have 1 question though, for line "while(!stack is empty() && temp == stack.peek().right)", why did you use while loop instead we can use 'if' statement for condition check? I am confused here.
@dharanyuvi6951
@dharanyuvi6951 3 жыл бұрын
"if" doesn't work bro Because imagine if you have a bit complicated tree with right node nested 3 times So, at that time think u traversed till the bottom right corner -> here u printed left and right nodes of the last bottom right family already -> now u have to jump back to pop and print the parent -> grandparent to finish the postOrder so "while" is the best fit -> especially temp == stack.peek.right plays a huge role. paper workout and debug to get more clear thoughts Thanks for asking
@raghuram463
@raghuram463 5 жыл бұрын
Does Non-recursive algorithm and Iterative algorithm mean the same for Post order traversal of Binary tree?
@vinutd210
@vinutd210 5 жыл бұрын
Yes. Iterative is a non-recursive algorithm, as we do not use a recursive call of our function here. Instead, we use our own stack to trace the tree. hope it helps.
@mnchester
@mnchester 3 жыл бұрын
great vid
@devendradahale546
@devendradahale546 3 жыл бұрын
Great 🙏
@SunnyKumar-wp6wp
@SunnyKumar-wp6wp 7 жыл бұрын
awsm.... bro
@waqasmalik6162
@waqasmalik6162 4 жыл бұрын
Aray bhai mouu say supari nikal kay bol xD
@987abhinav
@987abhinav 6 жыл бұрын
A little better solution (C#) internal void PostOrderTraversalUsingStack(Node cur) { Node temp = null; Stack s = new Stack(); while (cur != null || s.Count != 0) { if (cur != null) { s.Push(cur); cur = cur.left; } else { Node element = s.Peek(); if (element.right != null && element.right != temp) { cur = element.right; } else { temp = s.Pop(); Console.WriteLine(temp.data + ","); } } } }
@VishalSharma-hq5ti
@VishalSharma-hq5ti 4 жыл бұрын
Amazing!!
@sindhuprasad6964
@sindhuprasad6964 6 жыл бұрын
Does this algorithm work if there are duplicates in the tree?
@prashidell8980
@prashidell8980 5 жыл бұрын
It will go into infinite loop in case of duplicate.
@vinutd210
@vinutd210 5 жыл бұрын
@@prashidell8980 I am not sure if this is correct. When he compares to see if the popped node was the right of the root, he compares the object, and not just the value. Hence, it is not a duplicate. you pass an input of all nodes with same value, and it still will print the traversal. Please correct me if I am wrong.
@alexcomas2934
@alexcomas2934 5 жыл бұрын
Since you are comparing objects, you compare references (memory addresses) so your nodes will always be different even if they are identical.
@helentauro3850
@helentauro3850 7 жыл бұрын
It should go from right na? Which means 1,3,7.....
@xf99
@xf99 6 жыл бұрын
Postorder means check left node then right node then current. If you do a recursive postorder traversal you will end up with the order shown.
@akhileshkumar-xk7so
@akhileshkumar-xk7so 8 жыл бұрын
great work
@anshusharma1983
@anshusharma1983 6 жыл бұрын
The code becomes very simple if you can keep the track of visited nodes. Here is my version - public static void printPostOrderUsingStackAndVisited(Node root) { Stack stack = new Stack(); Set visited = new HashSet(); stack.push(root); while (!stack.isEmpty()) { Node current = stack.peek(); if (current.left != null && !visited.contains(current.left)) { stack.push(current.left); } else if (current.right != null && !visited.contains(current.right)) { stack.push(current.right); } else { visited.add(current); System.out.println(stack.pop().value); } } }
@davegould4940
@davegould4940 4 жыл бұрын
extra space
@TwinbeeUK
@TwinbeeUK 2 жыл бұрын
@@davegould4940 I would think the `contains()` operation will dramatically slow things down too if performance is a concern.
@kprabhudev
@kprabhudev 4 жыл бұрын
Thanks Tushar. Maybe, this could add to simplification too: void MyTree::postOrderTravIterative() { treeNode* p = this->root; stack st; while(p != nullptr || !st.empty()) { if(p != nullptr) { st.push(p); p = p->left; } else { treeNode* node = st.top()->right; if(node == nullptr) { do{ node = st.top(); cout data right); } else { p = node; } } } }
@AshishRanjan-ju7zk
@AshishRanjan-ju7zk 8 жыл бұрын
very nice...
@Chandyshot
@Chandyshot 5 жыл бұрын
Thanks Man
@ashok845
@ashok845 8 жыл бұрын
Nice
@veronicadey6731
@veronicadey6731 2 жыл бұрын
This is not an intuitive approach though if one has not practised enough
@ziminfan1664
@ziminfan1664 2 жыл бұрын
This is the most intuitive approach actually. It obeys the same way stack works in the recursive case.
@thanhsonhoang8982
@thanhsonhoang8982 4 жыл бұрын
thanks
@sukritkapil2562
@sukritkapil2562 4 жыл бұрын
thanks!!
@bighneshsabat5374
@bighneshsabat5374 8 жыл бұрын
nice..
@wasp4932
@wasp4932 7 жыл бұрын
why peek,not peak?
@xf99
@xf99 6 жыл бұрын
peek (at) means to take a look at something (or read, non-destructively); peak means the summit of a mountain, e.g.
@abhishekanand3706
@abhishekanand3706 6 жыл бұрын
2 is not twthooooo :))
@Tenacioustarantula
@Tenacioustarantula 7 жыл бұрын
Sounds a little complex and the explanation doesn't make it any easier ,can be better
@vishaltanawade7637
@vishaltanawade7637 4 жыл бұрын
Why are u talking in British English ,... Speak in Normal English .. you are from India not from London 😂😂😂😂
@dc6940
@dc6940 4 жыл бұрын
Its his choice, who are you to decide. If you dont like, dont watch the channel. He is helping people
@vishaltanawade7637
@vishaltanawade7637 4 жыл бұрын
@@dc6940 Sorry *Shaktimaan* 😂😂😝
@jamesqiu6715
@jamesqiu6715 8 жыл бұрын
Not your best work. Such a hurry from the begin to end ...
@yangwang24
@yangwang24 8 жыл бұрын
It seems like the postorder using traversal is difficult than preorder and inorder.
@lsdxsaurabh2798
@lsdxsaurabh2798 2 жыл бұрын
when you are a drunk and try to speak in english....
@niketandoddamani1093
@niketandoddamani1093 8 ай бұрын
Great Explanation
Largest BST in Binary Tree
9:43
Tushar Roy - Coding Made Simple
Рет қаралды 90 М.
Из какого города смотришь? 😃
00:34
МЯТНАЯ ФАНТА
Рет қаралды 2,6 МЛН
1, 2, 3, 4, 5, 6, 7, 8, 9 🙈⚽️
00:46
Celine Dept
Рет қаралды 116 МЛН
When u fight over the armrest
00:41
Adam W
Рет қаралды 33 МЛН
Iterative Postorder Traversal of Binary Tree
8:29
Tushar Roy - Coding Made Simple
Рет қаралды 79 М.
L10. iterative Inorder Traversal in Binary Tree | C++ | Java | Stack
11:14
Iterative Postorder Traversal of a Binary Tree | Animation
27:56
Dinesh Varyani
Рет қаралды 16 М.
Post Order Traversal of Binary Tree (Iterative Using 2 Stacks)
14:55
Morris Inorder Tree Traversal
11:44
Tushar Roy - Coding Made Simple
Рет қаралды 147 М.
Из какого города смотришь? 😃
00:34
МЯТНАЯ ФАНТА
Рет қаралды 2,6 МЛН