使用Stack的二叉搜索树的Inorder Tree Traversal算法

kri*_*hna 1 java stack inorder binary-search-tree

我的输入结果24, 4, 2, 3, 9, 10, 32,我得到了以下结果2, 3, 4, 24.

我正在使用堆栈.当我手动检查这个程序时else if,即使有正确的子树,节点也不会在堆栈上的4处进行.

public void inorderNonRcursive(Node root){

    Stack s = new Stack();
    Node node = root;
    Node k;
    int c=0;

    if(node != null) {
        s.push(node);    
    }

    while(!s.stack.isEmpty()) {   

        //node=(Node) s.stack.get(s.stack.size()-1);
        System.out.println("first condition" + (node.getleft() != null && (node.getVisited() == false)) + "second condi" + (node.getRight() != null));

        if(node.getleft() != null && (node.getVisited() == false)) {
            node = node.getleft();
            s.push(node);
            System.out.println("   from 1           "+(++c)); 

        } else if(node.getRight() != null) {
            k = s.pop();
            System.out.println(k.getvalue());
            node=node.getRight();
            s.push(node);
            System.out.println("    from 2          "+(++c)); 

        } else {
            k = s.pop();
            System.out.println(k.getvalue());
            System.out.println("        from 3      "+(++c)); 
        }  

    }

}
Run Code Online (Sandbox Code Playgroud)

and*_*256 9

对我来说,设计中存在两个问题:

  1. 该算法似乎是适用于迭代和算法的递归算法
  2. Node类知道被访问.

这是一个不同的解决方案(您需要稍微调整一下):

// Inorder traversal:
// Keep the nodes in the path that are waiting to be visited
Stack s = new Stack(); 
// The first node to be visited is the leftmost
Node node = root;
while (node != null)
{
    s.push(node);
    node = node.left;
}
// Traverse the tree
while (s.size() > 0)
{
    // Visit the top node
    node = (Node)s.pop();
    System.out.println((String)node.data);
    // Find the next node
    if (node.right != null)
    {
        node = node.right;
        // The next node to be visited is the leftmost
        while (node != null)
        {
            s.push(node);
            node = node.left;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

回头看我的第一条评论,你不是说你编写了伪代码并对其进行了测试.我认为这是编写新算法的关键步骤.