I'm learning the BST implementation, this is my code for insertion and inorder function. I have a doubt regarding the inorder function
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);
}
}
So when I try to use the bst.printinorder(root);
an error is thrown Cannot make a static reference to the non-static field root
.
So can I change the root to static or print the inorder by calling the inorder() function.Which is a better way??