我正在尝试通过BFS打印二叉树。
我的实现是使用PriorityQueue。 在开头我将root插入PriorityQueue。 然后在循环中,我从PriorityQueue中拉出一个节点,打印它,并将他的孩子(如果它们不为空)插入PriorityQueue。 为什么在插入第二个节点时,我得到了这个例外:
Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable
这是我的代码:
班主:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tree tree = new Tree();
}
}
类节点:
public class Node {
public Node(){}
public Node(int num)
{
value = num;
}
private int value;
private Node left;
private Node right;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
类树:
public class Tree {
private Node root;
public Tree()
{
root = new Node(5);
Node node2 = new Node(2);
Node node10 = new Node(10);
Node node8 = new Node(8);
Node node6 = new Node(6);
Node node15 = new Node(15);
root.setRight(node10);
root.setLeft(node2);
node10.setRight(node15);
node10.setLeft(node8);
node8.setLeft(node6);
printToWidth(root);
}
public void printToWidth(Node node)
{
PriorityQueue<Node> queue = new PriorityQueue<Node>();
queue.add(node);
while( !(queue.isEmpty()))
{
Node n = queue.poll();
System.out.println(n.getValue());
if (n.getLeft() != null)
queue.add(n.getLeft());
if (n.getRight() != null)
queue.add(n.getRight());
}
System.out.println("end printToWidth");
}
}
答案 0 :(得分:3)
你有两个选择:
使Node
实施Comparable<Node>
,以便可以根据natural ordering插入元素。这可能比较容易。
public int compareTo(Node other) {
return value - other.getValue();
}
使用custom Comparator<Node>
并在那里提供compare
方法,并具有初始容量。
PriorityQueue<Node> queue = new PriorityQueue<Node>(10, new Comparator<Node>() {
public int compare(Node left, Node right) {
return left.getValue() - other.getValue();
}
});
答案 1 :(得分:0)
例外情况告诉您,让Node
实施Comparable<Node>
。
您可以插入第一个节点,因为它没有可比较的内容,因此不需要进行比较。