有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java不能从内部类转换为类

我有一个包含内部类节点的BinaryTree类。 我想做的是通过调用树,在我的二进制树中插入一些节点。插入(节点)。但是,为了保持干净一致,我不想在节点内部类中创建一个insert()方法。因此,我尝试了下面的代码,但出现了一个错误:无法从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);
        }

    }

}

谢谢


共 (2) 个答案

  1. # 1 楼答案

    您不需要在insert方法内进行类型转换。应该是这样的:

    public void insert(Node n) {                             
       if(n.value > root.value)  
          insert(root.right);
    }
    
  2. # 2 楼答案

    要在树中插入节点,需要定义插入节点的位置,因此插入方法应类似于:

    //insert a new node right to a node. not null safe 
    public void insert(Node newNode, Node rightTo) {                                    
        newNode.right = rightTo.right;
        newNode.left = rightTo;
        rightTo.right = newNode;
    }
    

    它不需要浇铸
    要查找rightTo节点,可以使用:

    //get the last node which has a value lower than `value` 
    //may return null 
    public Node getNodeWithValueLowerThan(int value) {
        if(root == null) return null;
        return getNodeWithValueLowerThan(root, value);
    }
    
    //recursive method. null safe 
    private Node getNodeWithValueLowerThan(Node node, int value) {
        if(node == null) return null; 
        if(node.value > value) return node.left; //return previous node. may be null
        return getNodeWithValueLowerThan(node.right, value);
    }
    

    要将节点作为最后一个节点插入,可以使用:

    //insert a new node as last 
    public void insertLastNode(Node newNode) {
    
        Node lastNode = getTail();
        if(lastNode == null) {//empty tree 
            root = newNode;
            return;
        }
        newNode.left  = lastNode;
        lastNode.right = newNode;
    }
    

    其中getTail类似于:

    //find last node 
    private Node getTail() {
    
        if(root == null) return null;
        return getTail(root);
    }
    
    //recursive method to find last node. not null safe 
    private Node getTail(Node node) {
    
        if(node.right == null) return node;
        return getTail(node.right);
    }
    

    注意:代码没有经过测试,所以需要仔细调试