I seem to be having issues structuring a breadth-first tree.
In the code below, I have a node that is inserted through a loop in another class.
The structure of the tree is supposed to be as so:
A
/ \
B C
/\ /\
D E F G
Now for the code:
My code structures the left side correctly, whereas the right side adds the left side as well. I understand where in the code this happens, but is there a way to prevent this from happening?
public Node familyTree;
public void breadthFirst(Node newNode){
familyTree = breadthFirst(familyTree,newNode);
}
public Node breadthFirst(Node T, Node newNode){
if(T == null){
T = newNode;
return T;
}
if(T.left == null){
newNode.height = T.height + 1;
T.left = newNode;
return T;
}
else if(T.right == null){
newNode.height = T.height + 1;
T.right = newNode;
return T;
}
else{
T.left = breadthFirst(T.left, newNode);
T.right = breadthFirst(T.right, newNode); <-- this is the corporate
}
return T;
}