Iterative Postorder traversal of binary tree using one stack

Поделиться
HTML-код
  • Опубликовано: 29 сен 2024

Комментарии • 93

  • @santhosh087
    @santhosh087 4 года назад +16

    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!!.

  • @adityakrishna11
    @adityakrishna11 4 года назад +3

    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);
    }

  • @AshishRanjan-ju7zk
    @AshishRanjan-ju7zk 8 лет назад

    very nice...

  • @sukritkapil2562
    @sukritkapil2562 4 года назад

    thanks!!

  • @yelururao1
    @yelururao1 7 лет назад +11

    super explanation..thanks for it..please do more videos on BST , AVL and red-black tree

  • @waqasmalik6162
    @waqasmalik6162 4 года назад +3

    Aray bhai mouu say supari nikal kay bol xD

  • @uditgaba1450
    @uditgaba1450 4 года назад +2

    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+" ");
    }
    }

    }
    }

  • @abhinav4279_
    @abhinav4279_ 3 года назад +2

    This iterative traversal has been messing up my mind for long, not anymore.👍

  • @987abhinav
    @987abhinav 6 лет назад +1

    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 + ",");
    }
    }
    }
    }

  • @shreyasingh-sn4bs
    @shreyasingh-sn4bs 7 лет назад +13

    Thank you for making learning so much easier :)

  • @karthickm9846
    @karthickm9846 6 лет назад +3

    Great Video Tushar. In your code, you used, Stack stack = new LinkedList().. Is this correct?

    • @vinutd210
      @vinutd210 5 лет назад +1

      Good catch. I believe it is a typo. it should be Stack stack = new Stack();

    • @vinutd210
      @vinutd210 5 лет назад +6

      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;
      }
      }
      }
      }

  • @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.

  • @U2011-n7w
    @U2011-n7w Год назад +1

    nice explanation

  • @karanb2067
    @karanb2067 4 года назад +1

    explanation is great but algorithm implementation is a real head scratcher....you gotta mug it up for the most part.

  • @sanketkalokhe7400
    @sanketkalokhe7400 6 месяцев назад

    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

  • @sameer_sah
    @sameer_sah 3 года назад +1

    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.

  • @veronicadey6731
    @veronicadey6731 2 года назад +1

    So tough 🤯🤯🤯

  • @nking99t
    @nking99t 5 лет назад +1

    Can you do it without addFirst() or reverse()? otherwise which would just be another preorder traversal.

  • @ghostpieces2362
    @ghostpieces2362 4 года назад +2

    Tushar, this was an amazing visual walkthrough followed by a brilliant code walkthrough. Thanks for taking the time to share :)

  • @vvwu7194
    @vvwu7194 7 лет назад +3

    Thank you, better than the other explanations I have watched or read.

  • @sknayak3246
    @sknayak3246 5 лет назад +1

    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 лет назад +2

      we compare referenced to node, not the values of the nodes, otherwise youd be correct

  • @meghnasrivastava568
    @meghnasrivastava568 3 месяца назад

    Best explanation,I have watched so far!

  • @JangBahadur3028
    @JangBahadur3028 7 лет назад +2

    Awsome tutorial. well explained. Helped me a lot . Thank you Tushar.

  • @MrRanjeetaize
    @MrRanjeetaize 7 лет назад +2

    Nice explanation.. too much helping

  • @sureshiva4605
    @sureshiva4605 Год назад

    straigh forward way ....nice....instead of using previous variable or skip counts....this looks clean

  • @mprasanth18
    @mprasanth18 Год назад

    Thanks a lot. This is very helpfull.

  • @saksham9170
    @saksham9170 3 года назад +1

    Rote memorization at it's peak

    • @charan_75
      @charan_75 3 года назад +1

      They are standard algorithms. How else would you explain genius?

  • @student_03
    @student_03 Год назад

    thanks a lot sir
    amazing explanation

  • @paraskamboj1039
    @paraskamboj1039 3 месяца назад

    Thankyou so much sir

  • @ramakrishnaloka7946
    @ramakrishnaloka7946 4 года назад

    Is code handling the scenario of checking last popped element is equal to temp.right ???????

  • @TwinbeeUK
    @TwinbeeUK 2 года назад

    Possibly the clearest iterative postorder traversal of trees shown on RUclips! 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?

  • @avranj
    @avranj 2 года назад

    Where is this youtuber now?

  • @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?

  • @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.

  • @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()

  • @saisusritha
    @saisusritha 2 года назад

    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

  • @SonGoku-ep4wj
    @SonGoku-ep4wj 5 лет назад +1

    dude you're a legend . thank you !

  • @abhay7130
    @abhay7130 3 года назад

    bolne ke style sun ke gariyane ka hi man karta hai iske. baki sb badiya hai

  • @mingxiao1939
    @mingxiao1939 3 года назад

    Clear and intuitive explanation! Thank you Tushar.

  • @ragingpahadi
    @ragingpahadi 3 года назад +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;
    }

  • @SunnyKumar-wp6wp
    @SunnyKumar-wp6wp 7 лет назад +1

    awsm.... bro

  • @musheerahmed5815
    @musheerahmed5815 8 лет назад +1

    Brilliant. Thanks!!

  • @mnchester
    @mnchester 3 года назад

    great vid

  • @adhishmalviya2408
    @adhishmalviya2408 4 года назад

    this guy reminds me of song..**ek tu hi yaar mera mujhe kya duniya se lena**

  • @anshusharma1983
    @anshusharma1983 6 лет назад +2

    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.

  • @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.

  • @chenboxie6623
    @chenboxie6623 8 лет назад

    Thank you Tushar, very clear. Understand better now.

  • @MithleshKumar-iz1dz
    @MithleshKumar-iz1dz 5 лет назад

    You are saviour Tushar. Thanks alot!

  • @falakk22
    @falakk22 7 лет назад

    Superb Explanation Thanks!

  • @devendradahale546
    @devendradahale546 3 года назад

    Great 🙏

  • @thanhsonhoang8982
    @thanhsonhoang8982 4 года назад

    thanks

  • @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.

  • @vinayak186f3
    @vinayak186f3 3 года назад +2

    20 baar padhke bhool chuka hu , ek baar aur sahi 🙂

    • @KeshariPiyush24
      @KeshariPiyush24 3 года назад

      hota hai mere saath bhi hota hai.....kya kar sakte haiXD

  • @VishalSharma-hq5ti
    @VishalSharma-hq5ti 4 года назад

    Amazing!!

  • @Chandyshot
    @Chandyshot 5 лет назад

    Thanks Man

  • @DharminMajmudar
    @DharminMajmudar 6 лет назад

    Great explanation!

  • @abhishekanand3706
    @abhishekanand3706 6 лет назад +2

    2 is not twthooooo :))

  • @sindhuprasad6964
    @sindhuprasad6964 5 лет назад

    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 лет назад +4

      @@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 лет назад +1

      Since you are comparing objects, you compare references (memory addresses) so your nodes will always be different even if they are identical.

  • @bighneshsabat5374
    @bighneshsabat5374 8 лет назад

    nice..

  • @ashok845
    @ashok845 8 лет назад

    Nice

  • @akhileshkumar-xk7so
    @akhileshkumar-xk7so 8 лет назад

    great work

  • @shivamdixit8796
    @shivamdixit8796 8 лет назад +1

    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 :)

  • @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;
    }
    }
    }
    }

  • @vishaltanawade7637
    @vishaltanawade7637 4 года назад +2

    Why are u talking in British English ,... Speak in Normal English .. you are from India not from London 😂😂😂😂

    • @dc6940
      @dc6940 4 года назад +2

      Its his choice, who are you to decide. If you dont like, dont watch the channel. He is helping people

    • @vishaltanawade7637
      @vishaltanawade7637 4 года назад +1

      @@dc6940 Sorry *Shaktimaan* 😂😂😝

  • @Tenacioustarantula
    @Tenacioustarantula 7 лет назад +1

    Sounds a little complex and the explanation doesn't make it any easier ,can be better

  • @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 года назад +2

      "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

  • @lsdxsaurabh2798
    @lsdxsaurabh2798 2 года назад

    when you are a drunk and try to speak in english....

  • @wasp4932
    @wasp4932 6 лет назад

    why peek,not peak?

    • @xf99
      @xf99 6 лет назад +1

      peek (at) means to take a look at something (or read, non-destructively); peak means the summit of a mountain, e.g.

  • @jamesqiu6715
    @jamesqiu6715 8 лет назад +2

    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.