Error implementing Level Order Traversal Binary Search Tree with Java PriorityQueue

96 views Asked by At

I am trying to implement a level order traversal for my BST, but I am getting a weird error. Here is the code:

public void levelOrderTraverseTree(Node focusNode) {
    PriorityQueue<Node> currentLevel = new PriorityQueue<Node>();
    PriorityQueue<Node> nextLevel = new PriorityQueue<Node>();

    currentLevel.add(focusNode);

    while (!currentLevel.isEmpty()) {
        Iterator<Node> iter = currentLevel.iterator();
        while (iter.hasNext()) {
            Node currNode = iter.next();
            System.out.println(currentLevel.remove());
            System.out.println("adding "+currNode.leftChild+"to nextLevel");
            nextLevel.add(focusNode.leftChild);
            System.out.println("adding "+currNode.rightChild+"to nextLevel");
            nextLevel.add(focusNode.rightChild);
        }

        currentLevel = nextLevel;
        nextLevel.clear();

    }

}

When I try to run it, I get this error

Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable

on the line that adds focusNode.rightChild to the nextLevel queue, or nextLevel.add(focusNode.rightChild);

I am not sure why this error is occurring so any insight would be greatly appreciated.

1

There are 1 answers

0
Lucia Pasarin On BEST ANSWER

Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable means you must implement java.lang.Comparable interface in your Node class (something like:

public class Node implements Comparable {
    //...
})

) for your Node objects to be comparable to other nodes.