Non-recursive post-order traversal of binary tree (java)

When popping an element from the stack, check whether the right child node of the element and the top element of the stack are the same. If they are the same, it means that the traversal of the left and right subtrees has been completed. At this time, you only need to pop the top element of the stack. Once and output

void postOrderNonRecursive(BinaryTreeNode root){
    
    
  LLStack s = new LLStack();
  while(true){
    
    
    if(root != null){
    
    
      s.push(root);
      root = root.getLeft();
    }
    else{
    
    
      if(s.isEmpty()){
    
    
        System.out.println("Stack is empty");
        return;
      }
      else if(s.top().getRight() == null){
    
    
        root = s.pop();
        System.out.println(root.getData());
        if(root == s.top().getRight()){
    
    
          System.out.println(s.top().getData());
          s.pop();
        }
      }
      if(s.isEmpty()){
    
    
        root = s.top().getRight();
      }else{
    
    
        root = null;
      }

    }
  }
  s.deleteStack();
}

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/109653059