Java中二叉树的元素求和
我试图用递归和迭代的方法求二叉树的元素和。当递归的finde工作时,迭代给了我一个例外Java中二叉树的元素求和,java,binary-tree,Java,Binary Tree,我试图用递归和迭代的方法求二叉树的元素和。当递归的finde工作时,迭代给了我一个例外 import java.util.Queue; public class BinTree { public BinNode root; public boolean insertNode(BinNode bn) { BinNode child=null, parent=null; // Knoten suchen, nach welchem eingef
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;
}
}
import java.util.Queue;
公共类二叉树{
公共节点根;
公共布尔插入节点(BinNode bn){
BinNode子节点=null,父节点=null;
//这是一个很好的例子
子=根;
while(child!=null){
父母=子女;
if(bn.element==child.element)返回false;
如果(bn.element
队列q=newlinkedlist()给了我一个异常:
线程“main”java.lang.RuntimeException中的异常:不可编译的源代码-不兼容的类型:javaapplication34.LinkedList无法转换为java.util.Queue
有人能帮忙吗?给我一个启动或一个小的解释?我很不确定具体是什么问题
我没有在这里添加所有类,因为它们大多数都是常见的。但是如果需要,我会添加它们。看起来您在同一个包中定义了一个名为
LinkedList
的类,但它没有实现队列
如果要使用java.util.LinkedList
,则应导入或使用整个限定名。似乎您已在同一个包中定义了名为LinkedList
的类,但它未实现队列
如果您想使用java.util.LinkedList
,您应该导入或使用整个限定名。我们不知道特殊LinkedList
类的实现(只是它没有实现java.lang.Queue
接口),但如果您只说:
LinkedList q = new LinkedList();
(我假设这是一个任务,您必须使用这个特殊的LinkedList
来完成任务)我们不知道特殊的LinkedList
类的实现(只是它没有实现java.lang.Queue
接口),但是如果您说:
LinkedList q = new LinkedList();
(我假设这是一个作业,您必须使用这个特殊的LinkedList
来完成任务)您自己声明了LinkedList类吗?是的,我声明了,它错过了队列。我现在导入LinkedList,它工作正常。我的意思是,这很有效。它并没有达到我预期的效果,因为它给了我一个和递归版本不同的和。你们自己声明了LinkedList类吗?是的,我声明了,但它错过了队列。我现在导入LinkedList,它工作正常。我的意思是,这很有效。它没有达到我的预期,因为它给了我比递归版本更多的总和。谢谢。真的很容易,很高兴听到。如果你觉得这个答案有帮助,请不要忘记接受。谢谢。真的很容易,很高兴听到。如果你觉得这个答案有用,请不要忘记接受。