I am trying to write a binary tree recursive insertion and I not getting anywhere for last hours. I either get a stackoverflow error or not all items are being inserted.
I want to insert these values in my tree:
binaryTree.addNodeRecursion(new MNode(50, "fourth"))
binaryTree.addNodeRecursion(new MNode(25, "third"))
binaryTree.addNodeRecursion(new MNode(15, "second"))
binaryTree.addNodeRecursion(new MNode(10, "first"))
binaryTree.addNodeRecursion(new MNode(75, "fifth"))
binaryTree.addNodeRecursion(new MNode(85, "sixth"))
I want to do this without passing the root around as a parameter. So my code looks like this:
public void addNodeRecursion(MNode newNode){
if(root == null) {
root = newNode
}else{
addRecurs(newNode); //this is the recursive function, it should not return a node object
}
}
Note, that I am not talking about a Binary Search Tree but a Binary tree, where elements order is not relevant. I care about how elements are inserted. I want to insert them as it is show below:
1 Step:
50
2 Step:
50
/
25
3 Step:
50
/ \
25 15
4 Step:
50
/ \
25 15
/
10
5 Step:
50
/ \
25 15
/ \
10 75
6 Step: (now notice that I am going back to the sibling of the current parent)
50
/ \
25 15
/ \ /
10 75 85
Now here is my addRecurs function:
private void addRecurs(MNode newNode) {
if(newNode == null) { return };
if(root.leftNode == null){ //Step 2 if the left node is null assign it
root.leftNode = newNode
}else{ //Else that means the right Node is null
root.rightNode = newNode // Step 3 set the right node
root = root.leftNode // the the parent to the left node
addRecurs(newNode) // repeat
}
};
It doesn't work.
Can this be done without tracking or storing the parent in a variable?