import java.util.*;
public class buildBST {
private class Node{
Node left;
Node right;
int data;
Node(){
left=null;
right=null;
data=0;
}
}
private static Node root;
public static void constract(int ar[]){
root=constract(ar,0,ar.length);
}
private static Node constract(int ar[],int low,int high) {
if(low>=high)
{
return null;
}
int mid=(low + high)/2;
Node nn=new Node();
nn.data=ar[mid];
nn.left=constract(ar,low,mid);
nn.right=constract(ar,mid+1,high);
return nn;
}
public static void preOrder(Node node) {
if(node==null)
return;
System.out.print(node.data+" ");
preOrder(node.left);
preOrder(node.right);
}
public static void main(String args[]) {
Scanner scn=new Scanner(System.in);
int t=scn.nextInt();
while(t!=0){
int n=scn.nextInt();
int ar[]=new int[n];
for(int i=0;i<n;i++){
ar[i]=scn.nextInt();
}
constract(ar);
preOrder(root);
t–;
}
}
}
How to fix this error-> buildBST.java:18: error: non-static variable this cannot be referenced from a static context Node nn=new Node(); in this my code
@sksumitkumardiwaker,
Don’t use static in construct. Make object of main and then call construct. https://ide.codingblocks.com/s/197586 corrected code.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
Instance variables (variables defined in the class but not marked as static keyword) cannot be accessed from a static method without referencing an instance of the class. An attempt to use the variables and methods of the class which do not have the static modifier without creating an instance of the class is caught by the Java compiler at compile time and flagged as an error: Cannot Be Referenced From a Static Context . For ex. Java main() method cannot access a non-static member of its class. That means, public static void main(String[] args) is a static method.
Solutions:
- Either make that variable static.
- Make the calling function non-static.
- Inside the calling function, create an object first and then access the non-static variable.