I am trying to insert node in a binary tree using recursive method. But once its out of the method the root becomes the new node and left child and right child are null. With this I'm trying to learn how recursion works. Also, does recursive method always has to return something. Below is the code.
public class BinaryNode {
int key;
BinaryNode left;
BinaryNode right;
public BinaryNode( int key){
this.key = key;
// this.left = left;
//this.right = right;
}
}
public class BinaryTree {
BinaryNode root;
public void insert(int key){
BinaryNode newNode = new BinaryNode(key);
if(root == null){
root = newNode;
}else{
BinaryNode focusNode = root;
BinaryNode parent;
while(true){
parent = focusNode;
if(key<focusNode.key){
focusNode = focusNode.left;
if(focusNode==null){
parent.left= newNode;
return;
}
}else{
focusNode = focusNode.right;
if(focusNode==null){
parent.right= newNode;
return;
}
}
}
}
}
public BinaryNode recursiveInsert(int key, BinaryNode node){
BinaryNode newNode = new BinaryNode(key);
if (node == null){
root = newNode;
}
else{
if(key < node.key){
root.left = recursiveInsert(key, node.left);
}
else{
root.right = recursiveInsert(key, node.right);
}
}
return root;
}
public String toString(){
String toTree = null;
return toTree;
}
public static void main(String[]args){
BinaryTree tree = new BinaryTree();
tree.recursiveInsert(7, tree.root);
tree.recursiveInsert(6, tree.root);
tree.recursiveInsert(4, tree.root);
tree.recursiveInsert(8, tree.root);
tree.recursiveInsert(9, tree.root);
tree.recursiveInsert(5, tree.root);
}
}
The method I'm trying is recursiveInsert. Thanks!!
I suppose the problem comes from
You are traversing the tree and in the last step you are asking the left/right child of a leaf node. This hasn't one, so it's child is null. This is the value returned by the recursive calls and in the end, it gets assigned to root.
To fix this, before descending into a node, make sure that child node exists.
Also this is a bit weird
It should be
node
and notroot
.