二叉搜索树,inorder 方法迭代不起作用

Binary Search tree, inorder method iterative not working

我目前正在大学学习数据结构 class,我们正在学习使用链表的二叉搜索树。我们已经递归地检查了 inOrder 方法,但我想尝试迭代地执行该方法。经过一些研究,我意识到我必须在遍历树时使用堆栈。我能够到达树最左侧的尽头,但是向后遍历树是我遇到麻烦的地方。我已经尝试了我的代码的各种版本,但我总是以 nil 指针异常结束,或者它打印出乱序。

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

   }

}

首先,您的代码存在两个主要缺陷:您离开了第一个 while 循环,当前指向 null,因此您永远不会进入第二个 while 循环。而且,我觉得这个

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

应该用 myStack.push(current.getRight()); 更正,否则你只是试图将你弹出的元素推来推去,你会进入一个无限循环。但即便如此,探索的逻辑也是错误的,因为你永远不会走到你从右边 link 到达的节点的左边。 我试图从您的代码开始并创建一个有效的中序遍历:

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

      }
   }

}

据我所知,您的代码在第二个 while 循环中存在一些问题。您的想法是正确的,但是存在一些逻辑错误。你的条件是对的,但不应该在一起,应该分开。下面的代码实现了你正在寻找的东西。

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

}