我想用递归和迭代方法求和二叉树的元素。虽然递归的工作正常,迭代给了我一个例外。Java中二叉树的元素求和
import java.util.Queue;
public class BinTree {
public BinNode root;
public boolean insertNode(BinNode bn) {
BinNode child=null, parent=null;
// Knoten suchen, nach welchem eingefuegt wird
child = root;
while(child != null) {
parent = child;
if (bn.element == child.element) return false;
else if (bn.element < child.element) child = child.left;
else child = child.right;
}
// Baum leer?
if (parent==null) root = bn;
// Einfuegen nach parent, links
else if (bn.element < parent.element) parent.left = bn;
// Einfuegen nach parent, rechts
else parent.right = bn;
return true;
}
public BinNode findNode(int value) {
BinNode n = root;
while (n != null) {
if (value == n.element) { return n; }
else if (value < n.element) { n = n.left; }
else { n = n.right; }
}
return null;
}
public String toString() {
return root.toString();
}
//Max des Gesamtbaumes
public int max(){
if(root==null){
return 0;
}
else {
return root.max();
}
}
//(Iterativ)
public int max2(){
//The line that throws out the exception
Queue q = new LinkedList();
int sum = 0;
if(root!=null){
q.add(root);
}
while(!q.isEmpty()){
BinNode node = (BinNode) q.remove();
if(node.left == null && node.right == null){
sum = sum + node.element;
}
else{
if(node.left != null){
q.add(node.left);
}
}
if(node.right != null){
q.add(node.right);
}
}
return sum;
}
}
的Queue q = new LinkedList();
在MAX2,方法是给我的异常: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: javaapplication34.LinkedList cannot be converted to java.util.Queue
谁能帮助吗?给我一个kickstart或一个小解释?我很不确定详细的问题。
我没有在这里添加每个班级,因为他们大多数都很常见。但如果需要,我会添加它们。
你是否自己声明了一个LinkedList类? –
是的,我错过了队列。我现在importet LinkedList,它工作得很好。我的意思是,它的工作。它没有达到我的预期,因为它比我的递归版本提供了另一个总和。 –