gpt4 book ai didi

java - Java中二叉树的元素求和

转载 作者:行者123 更新时间:2023-12-01 21:08:26 25 4
gpt4 key购买 nike

我正在尝试使用递归和迭代方法对二叉树的元素求和。虽然递归可以找到结果,但迭代却给了我一个异常(exception)。

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

}
max2-Method 中的 Queue q = new LinkedList(); 给了我异常: 线程“main”中的异常 java.lang.RuntimeException:无法编译的源代码 - 不兼容的类型:javaapplication34.LinkedList 无法转换为 java.util.Queue

有人可以帮忙吗?给我一个启动或一些解释吗?我非常不确定具体是什么问题。

我没有在这里添加每个类,因为它们中的大多数都是常见的。但如果需要的话我会添加它们。

最佳答案

您似乎在同一个包中定义了一个名为 LinkedList 的类,但它没有实现 Queue

如果您想使用java.util.LinkedList,您应该导入或使用整个限定名称。

关于java - Java中二叉树的元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41796517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com