【发布时间】:2020-11-26 18:30:14
【问题描述】:
我正在尝试实现一棵二叉树,更具体地说,我正在尝试编写在树中插入节点的方法。
一个节点由一个整数键(用于节点的位置)和一个String 值(节点内部的值)组成。
下面的代码是针对节点类的:
public class Node {
private int key;
private String value;
private Node left;
private Node right;
public Node(int key, String value){
this.key = key;
this.value = value;
this.left = null;
this.right = null;
}
public void setLeftChild(Node child) {
left = child;
}
public void setRightChild(Node child) {
right = child;
}
public int getValue() { return key; }
public Node getLeftChild() { return left; }
public Node getRightChild() { return right; }
public int getKey(){ return key; }
}
这是树类:
public class BinaryTree {
private static Node root;
public BinaryTree(){
root = null;
}
public BinaryTree(int key, String string) {
root = new Node(key,string);
}
public void insertValue(int key, String value) {
insert(key, value, root);
}
public void insert(int key, String value, Node currentNode) {
//base case
if (currentNode == null) {
currentNode = new Node(key, value);
} else {
if ( key <= currentNode.getKey())
insert(key, value, currentNode.getLeftChild());
else {
if ( key > currentNode.getKey())
insert(key, value, currentNode.getRightChild());
}
}
}
public static void main(String[] args){
BinaryTree alpha = new BinaryTree(5,"Bella");
insertValue();
}
}
我从 Java 收到以下错误:
错误:(32, 9) java: 不能从静态上下文引用非静态方法 insertValue(int,java.lang.String)
我不明白为什么。有人可以向我解释为什么它不起作用吗?想法正确吗?递归调用正确吗?
【问题讨论】:
-
很明显——你在哪个对象上调用
insertValue方法? -
是的,对不起,无论如何,如果我插入 insertValue(3,"Alpha") 我有错误
-
很抱歉,但这并不能回答我的问题。即使您认为可以使用
insertValue(3, "Alpha")之类的表达式调用该方法,但您不能——您想在哪个对象上调用该方法? -
抱歉,我读的问题太快了。我还没有调用对象的方法。是一个愚蠢的错误。
标签: java recursion binary-tree nodes non-static