【问题标题】:Traversal of Binary Search Tree via loop instead of Recursion通过循环而不是递归遍历二叉搜索树
【发布时间】:2014-12-04 02:48:31
【问题描述】:

有谁知道如何使用循环而不是递归来遍历二叉搜索树?

我有递归方法

public static int countMatches(BinaryNodeInterface<Integer> tree, Integer key)
{
    int matches = 0;
    if (tree != null)
    {
        if (tree.getData().equals(key))
            matches++;
        matches += countMatches(tree.getLeftChild(), key);
        matches += countMatches(tree.getRightChild(), key);
    }
    return matches;
}

【问题讨论】:

  • 请缩进您的代码。在缩进之前我无法真正查看...
  • 是的,我知道。你也想通了吗?

标签: java tree binary-tree binary-search-tree tree-traversal


【解决方案1】:

您可以使用队列进行级别顺序遍历

public static int countMatches(BinaryNodeInterface<Integer> tree, Integer key)
{
    int matches = 0;
    if (tree == null) return 0;
    Queue<BinaryTreeNodeInterface<Integer>> queue = new LinkedList<BinaryTreeNodeInterface<Integer>>();
    queue.add(tree);
    while (!queue.isEmpty()) {
        BinaryTreeNodeInterface<Integer> current = queue.remove();
        if (current.getData().equals(key)) 
            matches++;
        if (current.getLeftChild() != null)
            queue.add(current.getLeftChild());
        if (current.getRightChild() != null)
            queue.add(current.getRightChild());
    }

    return matches;
}

【讨论】:

    【解决方案2】:

    一个简单的方法是使用一个列表,它首先在广度上贯穿它。

    public static int countMatches(BinaryNodeInterface<Integer> tree, Integer key)
    {
        ArrayList<Node> open = new ArrayList<Node>();
        open.add(tree.getRoot());
        int matches = 0;
        while(!open.isEmpty())
        {
            if(open.get(0).hasLeft())
                open.add(open.get(0).getLeftChild());
            if(open.get(0).hasRight())
                open.add(open.get(0).getRightChild());
            if(open.get(0).equals(key))
                ++matches;
    
            open.remove(0);
        }
        return matches;
    }
    

    这可能不是最有效的方法,但它应该可以满足您的要求。 这个是深度优先的,但如果你需要,将它改为广度优先对你来说应该不会太难。

    【讨论】:

    • 实际上 Eric 可能是一个更好的选择,因为在数组列表上使用 Que 可能更容易组织
    猜你喜欢
    • 2020-09-25
    • 2013-05-12
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多