Тёмный

Iterative Postorder traversal of binary tree using one stack 

Tushar Roy - Coding Made Simple
Подписаться 245 тыс.
Просмотров 116 тыс.
50% 1

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

 

21 окт 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 93   
@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
@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+" "); } } } }
@meghnasrivastava568
@meghnasrivastava568 4 месяца назад
Best explanation,I have watched so far!
@vvwu7194
@vvwu7194 7 лет назад
Thank you, better than the other explanations I have watched or read.
@ghostpieces2362
@ghostpieces2362 4 года назад
Tushar, this was an amazing visual walkthrough followed by a brilliant code walkthrough. Thanks for taking the time to share :)
@mingxiao1939
@mingxiao1939 3 года назад
Clear and intuitive explanation! Thank you Tushar.
@yelururao1
@yelururao1 7 лет назад
super explanation..thanks for it..please do more videos on BST , AVL and red-black tree
@shreyasingh-sn4bs
@shreyasingh-sn4bs 7 лет назад
Thank you for making learning so much easier :)
@sameer_sah
@sameer_sah 3 года назад
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.
@U2011-n7w
@U2011-n7w Год назад
nice explanation
@sureshiva4605
@sureshiva4605 Год назад
straigh forward way ....nice....instead of using previous variable or skip counts....this looks clean
@JangBahadur3028
@JangBahadur3028 7 лет назад
Awsome tutorial. well explained. Helped me a lot . Thank you Tushar.
@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 :)
@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.
@chenboxie6623
@chenboxie6623 8 лет назад
Thank you Tushar, very clear. Understand better now.
@TwinbeeUK
@TwinbeeUK 2 года назад
Possibly the clearest iterative postorder traversal of trees shown on RU-vid! 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?
@MrRanjeetaize
@MrRanjeetaize 7 лет назад
Nice explanation.. too much helping
@student_03
@student_03 Год назад
thanks a lot sir amazing explanation
@abhay7130
@abhay7130 3 года назад
bolne ke style sun ke gariyane ka hi man karta hai iske. baki sb badiya hai
@abhinav4279_
@abhinav4279_ 3 года назад
This iterative traversal has been messing up my mind for long, not anymore.👍
@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; } } } }
@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.
@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); }
@SonGoku-ep4wj
@SonGoku-ep4wj 5 лет назад
dude you're a legend . thank you !
@niketandoddamani1093
@niketandoddamani1093 7 месяцев назад
Great Explanation
@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()
@falakk22
@falakk22 7 лет назад
Superb Explanation Thanks!
@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 ???????
@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
@adhishmalviya2408
@adhishmalviya2408 4 года назад
this guy reminds me of song..**ek tu hi yaar mera mujhe kya duniya se lena**
@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
@paraskamboj1039
@paraskamboj1039 3 месяца назад
Thankyou so much sir
@DharminMajmudar
@DharminMajmudar 6 лет назад
Great explanation!
@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.
@musheerahmed5815
@musheerahmed5815 8 лет назад
Brilliant. Thanks!!
@veronicadey6731
@veronicadey6731 2 года назад
So tough 🤯🤯🤯
@sanketkalokhe7400
@sanketkalokhe7400 7 месяцев назад
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
@SunnyKumar-wp6wp
@SunnyKumar-wp6wp 7 лет назад
awsm.... bro
@saksham9170
@saksham9170 4 года назад
Rote memorization at it's peak
@charan_75
@charan_75 3 года назад
They are standard algorithms. How else would you explain genius?
@karanb2067
@karanb2067 4 года назад
explanation is great but algorithm implementation is a real head scratcher....you gotta mug it up for the most part.
@mnchester
@mnchester 3 года назад
great vid
@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
@devendradahale546
@devendradahale546 3 года назад
Great 🙏
@akhileshkumar-xk7so
@akhileshkumar-xk7so 8 лет назад
great work
@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.
@avranj
@avranj 2 года назад
Where is this youtuber now?
@waqasmalik6162
@waqasmalik6162 4 года назад
Aray bhai mouu say supari nikal kay bol xD
@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; } } } }
@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.
@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.
@AshishRanjan-ju7zk
@AshishRanjan-ju7zk 8 лет назад
very nice...
@ashok845
@ashok845 8 лет назад
Nice
@Chandyshot
@Chandyshot 5 лет назад
Thanks Man
@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?
@thanhsonhoang8982
@thanhsonhoang8982 4 года назад
thanks
@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.
@bighneshsabat5374
@bighneshsabat5374 8 лет назад
nice..
@sukritkapil2562
@sukritkapil2562 4 года назад
thanks!!
@wasp4932
@wasp4932 6 лет назад
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....
@saisusritha
@saisusritha 2 года назад
Great Explanation
Далее
Largest BST in Binary Tree
9:43
Просмотров 89 тыс.
Iterative Postorder Traversal of Binary Tree
8:29
Просмотров 79 тыс.
DIY Pump Solutions
00:18
Просмотров 1,2 млн
Morris Inorder Tree Traversal
11:44
Просмотров 146 тыс.
Iterative Postorder Traversal using one stack
34:48
Просмотров 24 тыс.
Iterative Inorder Traversal of Binary Tree
10:30
Просмотров 121 тыс.
String Permutation Algorithm
25:09
Просмотров 320 тыс.
Check if Binary Tree is Binary Search Tree
10:29
Просмотров 122 тыс.
Level by Level Printing of Binary Tree
15:37
Просмотров 66 тыс.