I am solving the question Link and the logic is very easy. But I found weird behavior when I executed the code. As far as I know in java, if I give any object from main to any method and that method modifies object,then the object from main is modified as it was being referenced. But I am not getting why this is not happening in my code and it is always giving nullpointerexception. Below is my code.`
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
static class Node
{
int val;
Node left,right;
Node(int val)
{
this.val=val;
this.left=null;
this.right=null;
}
}
static int n;
static int[] a;
public static void insert(Node root,int left,int right)
{
int num=right-left+1;
root=new Node(a[left+num/2]);
if(num==1)
return;
insert(root.left,left,left+num/2-1);
insert(root.right,left+num/2+1,right);
}
public static void preorder(Node root)
{
System.out.print(root.val+" ");
if(root.left!=null)
preorder(root.left);
if(root.right!=null)
preorder(root.right);
}
public static void main (String[] args) {
Scanner in=new Scanner(System.in);
int tc=in.nextInt();
while(tc-->0)
{
n=in.nextInt();
a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
}
Node root=null;
insert(root,0,n-1);
preorder(root);
}
}
}`