To insert data in a binary search tree, you first need to find the location where the data is inserted. Following the same mechanism as the search operation, you can find the insertion location. When the insertion location is found, if the data already exists, then just ignore and Return, otherwise, insert the data into the last position of the path traversed
BinarySearchTreeNode insert(BinarySearchTreeNode root,int data){
if(root == null){
root = new BinarySearchTreeNode();
if(root == null){
System.out.println("Out of memory!");
}else{
root.setData(data);
root.setLeft(null);
root.setRight(null);
}
}else{
if(data < root.getData()){
root.setLeft(insert(root.getLeft()),data);
}else if(data > root.getData()){
root.setRight(insert(root.getRight()),data);
}
}
return root;
}