【问题标题】:Inorder Tree Traversal algorithm for a Binary Search Tree using Stack使用堆栈的二叉搜索树的中序树遍历算法
【发布时间】:2012-09-23 21:59:35
【问题描述】:

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

我正在使用 堆栈。当我手动检查此程序时,即使有正确的子树,节点也不会在堆栈上的 4 处通过 else if

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

    }

}

【问题讨论】:

  • 你能贴出你的Node类的代码吗?

标签: java stack binary-search-tree inorder


【解决方案1】:

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

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

回想起我的第一个 cmets,您并没有说您编写了伪代码并对其进行了测试。我认为这是编写新算法的关键一步。

【讨论】:

    【解决方案2】:

    这看起来像是一个课堂练习,旨在帮助您理解二叉树。

    在你写任何代码之前,画一张你的树的图,每个节点都有一个值,比如“A”、“B”、“C”等。然后从根节点开始,看看你需要什么按顺序访问每个节点。用伪代码写下你学到的东西,并按照它所说的来测试它。确保为每个节点测试你能想到的所有不同情况(你应该至少有三个)。在树中放置大约七个节点。

    现在您可以开始编写代码了。将您的伪代码键入为 cmets,然后在每个注释之间插入您的 Java 代码。

    享受:-)

    【讨论】:

    • 感谢您的建议,但这不是 xlass 练习,我已经使用节点圈测试它并逐步通过,我还打印了 eveey 单次迭代的条件,以了解实际发生的情况。实际问题是我有一个正确的节点 9 用于 4 个节点,即使它有一个正确的节点,它没有采用第二个条件,即我正在检查正确的节点是否为真。在我开始这个之前,我还使用了递归方法,这给了我完美的答案。
    猜你喜欢
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多