我有一个 BinaryTree 类,其中包含一个内部类 Node。 我想做的是能够通过调用 tree.insert(node) 在我的 BinaryTree tree 中插入一些节点。但是,为了保持干净和一致,我不想在 Node 内部类中创建 insert() 方法。所以我尝试了下面的代码,但出现错误:无法从 BinaryTree.Node 转换为 BinaryTree。
我应该做什么?
二叉树类
public class BinaryTree {
Node root = null;
private class Node {
int value;
Node left;
Node right;
}
public BinaryTree(int v) {
root.value = v;
root.left = null;
root.right = null;
}
public void insert(Node n) {
/* Error */
if(n.value > root.value) ((BinaryTree) root.right).insert(n);
}
}
主类
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String[] str = sc.nextLine().split(" ");
BinaryTree tree;
for(int i = 0; i < str.length-1; i++) {
int val = Integer.parseInt(str[i]);
//tree.insert(node);
}
}
}
谢谢
最佳答案
您不需要在 insert
方法中进行类型转换。应该是这样的:
public void insert(Node n) {
if(n.value > root.value)
insert(root.right);
}
关于java - 无法从内部类转换到类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48714451/