2

Does anyone know how to traverse a binary search tree using loops instead of recursion?

I have the recursive method

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;
}
2
  • PLEASE indent your code. I can't really look at until it's indented... Commented Dec 4, 2014 at 2:50
  • 1
    Yes, I know. Have you figured it out too? Commented Dec 4, 2014 at 2:50

2 Answers 2

1

You can use do a level order traversal using a queue

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

A simple approach would be to use a List that runs through it either dept of breadth first.

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

This is probably not the most efficient way of doing it but it should work for what your asking. This one works depth first but it shouldn't be too hard for you to change it to breadth first if you need.

1 Comment

Actually Eric's is probably a better alternative since using a Que over an array list is probably easier to organise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.