【发布时间】:2021-07-15 17:20:12
【问题描述】:
我正在学习 BST 实现,这是我的插入和中序函数代码。我对中序函数有疑问
public class BSTtry {
Node root;
class Node{
int data;
Node left,right;
Node(int data){
this.data=data;
left=right=null;
}
}
public void insert(int data) {
root=insertdata(root,data);
}
public void inorder(){
printinorder(root);
}
public Node insertdata(Node root,int data) {
if(root==null) {
root=new Node(data);
return root;
}
if(data<root.data) {
root.left=insertdata(root.left,data);
}
if(data>root.data) {
root.right=insertdata(root.right,data);
}
return root;
}
public void printinorder(Node root) {
if(root!=null) {
printinorder(root.left);
System.out.print(root.data+" ");
printinorder(root.right);
}
}
public static void main(String[] args) {
BSTtry bst=new BSTtry();
//Inserted some values in the tree
bst.printinorder(root);
}
}
所以当我尝试使用 bst.printinorder(root); 时,会抛出错误Cannot make a static reference to the non-static field root。
那么我可以通过调用 inorder() 函数将根更改为静态或打印中序。哪个是更好的方法??
【问题讨论】:
-
同一个问题之前被问过很多次,并且已经回答了很多次,以至于已经有 10 个重复了。请先搜索,然后准备,然后再决定是否询问。
标签: java static binary-search-tree