在二叉搜索树中插入数据,首先需要找到插入该数据的位置,遵循与寻找操作相同的机制,就能够找到插入的位置,当找到插入位置时,如果该数据已经存在,那么只需要忽略并且返回,否则,将该数据插入走过的路径的最后位置上
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;
}