I want to implement a Binary Tree in java and i have a problem with the nodes.The problem is that i can't save the newN in the root node. Everytime i try to insert a new node, the root is null and the pointer doesn't point to the newN address.When i find a node that is null i want to make him point to a newN(a node with info==x and left and right children on null).How can i fix this?
public class Node {
public int info;
public Node left;
public Node right;
Node(int info) {
this.info = info;
}
}
public class BTree {
public Node root;
BTree() {
root = null;
}
public void add(int x) {
insert(root, x);
}
public boolean insert(Node r, int x) {
if (r == null) {
r = new Node(x);
return true;
}
else{
if (r.info == x) {
System.out.println("the value has already been added");
return false;
}
if (r.info < x)
insert(r.left, x);
if (r.info > x)
insert(r.right, x);
}
return false;
}
public void inOrder() {
inOrderTraverse(root);
}
public void inOrderTraverse(Node r) {
if (r != null) {
inOrderTraverse(r.left);
System.out.print(r.info + " ");
inOrderTraverse(r.right);
}
}
}
public class Main {
public static void main(String args[]){
BTree bt=new BTree();
bt.add(10);
bt.add(5);
bt.add(3);
bt.add(2);
bt.inOrder();
}
}
PS:I know there are no pointers in Java and all the function calls are made with the address , not the value.Isn't insert(Node r,int x) equivalent with insert(Node &r,int &r) from c++?