Binary search tree, iterator inorder method not working

I am currently taking a college data structure class and we are exploring binary search trees using linked lists. We switched the inOrder method recursively, but I wanted to try to make the method iterative. After some research, I realized that I should use the stack when I cross a tree. I can get the end of the left side of the tree, but the intersection of the tree is where I am having problems. I tried a different version of my code, but I continue to end up with an nil pointer exception or print out of order.

public void inOrder(){                
    // implement this method using non-recursive solution
   if(m_root==null){
      return;
   }
   Stack<BSTNode> myStack= new Stack<BSTNode>();
   BSTNode current=m_root;
   while (current!= null){
      myStack.push(current);
      current=current.getLeft();
   }
   while (current!=null&& !myStack.isEmpty()){
      current=myStack.peek();
      System.out.print(current.getInfo()+" ");
      myStack.pop();
      if(current.getRight()!=null){
          myStack.push(current);
      }

   }

}
+4
source share
2 answers

, , . , , , . , , , , . , .

public void inOrder(){                
    // implement this method using non-recursive solution
   if(m_root==null){
      return;
   }
   Stack<BSTNode> myStack= new Stack<BSTNode>();
   BSTNode current=m_root;
   while (current!= null){
      myStack.push(current);
      current=current.getLeft();
   }
   while (!myStack.isEmpty()){
      current=(BSTNode)myStack.pop();
      System.out.print(current.getInfo()+" ");
      if(current.getRight() != null){
         current=current.getRight();
         while (current!= null){
            myStack.push(current);
            current=current.getLeft();
         }
      }
   }

}
+5

: while , , , , while. , ,

if(current.getRight()!=null){
      myStack.push(current);
  }

myStack.push(current.getRight());, , , . , node, . :

public void inOrder(){                

   Stack<BSTNode> myStack= new Stack<BSTNode>();
   Set<BSTNode> visited = new HashSet<BSTNode>();
   BSTNode current = m_root;
   if(current!= null)
       myStack.push(current);
   while (!myStack.isEmpty()){
      current = myStack.peek();
      if(current.getLeft()!= null && !visited.contains(current.getLeft()))
          myStack.push(current.getLeft());
      else{
          //here you explore the parent node
          System.out.print(current.getInfo()+" ");
          visited.add(current);
          myStack.pop();
          //and then you see if it has children on the right
          if(current.getRight()!=null && !visited.contains(current.getRight))
              myStack.push(current.getRight());

      }
   }

}
+2

Source: https://habr.com/ru/post/1619001/


All Articles