public void recurInsert(BinaryTree.Node root, BinaryTree.Node newNode, int height) {
if (newNode == null) {
System.out.println("InsertNode is empty, please create new one");
return;
}
else{
if (height == 1) {
if (root == null)
return;
else if (root.leftChild == null) {
root.leftChild = newNode;
System.out.println("left" + newNode.data);
}
else {
root.rightChild = newNode;
System.out.println("right" + newNode.data);
}
}
else{
if (root.leftChild != null)
recurInsert(root.leftChild, newNode, height-1);
//else (root.rightChild != null)
// recurInsert(root.rightChild, newNode, height-1);
if (root.rightChild != null)
recurInsert(root.rightChild, newNode, height-1);
}
}
}
This is the code I implemented, but it actually inserts two same nodes to make it balance. Can anyone help me to fix the bug or implement it in another way?
I just want to implement an insertion for a complete binary tree using recursion . Say inserting a node with a sequence A,B,C,D,E,F. It comes like root is A and its left child is B, and right child is C and B's children are D and E,and C's left child is F.
My code has bug but implemented this insertion to make the tree is binary complete tree. It comes like A's children are B and C. But B's children is D,E and C's children is D and E as well instead of F. So hope you guys can help me to fix the bug or to implement it in another way using recursion.
Fortunately. I've seen a similar question posted on Stack Overflow, but I want to implement it using recursion, not with additional data structure.