I have the following method that I'm using (uses the Breadth-first traversal algorithm) to add items into a Binary Tree in consecutive order.
For instance, if I had
A
/ \
B C
/
D
I would want the next addition to be:
A
/ \
B C
/ \
D E
My problem lies in the fact that I'm not sure how to return the value properly. I know that when we encounter the first null node, that's where we insert the value, but what do we insert it into? If we insert it into the Binary Tree we're getting from the queue, that's a sub-tree of the root (or the tree we're trying to add to) so returning that won't be the full tree.
Here's the code I have:
public static <T> BinaryTree<T> addToTree(BinaryTree<T> t1, BinaryTree<T> t2) {
Queue<BinaryTree<T>> treeQueue = new LinkedList<BinaryTree<T>>();
while (t1 != null) {
if (t1.getLeft() == null) {
t1.attachLeft(t2);
break;
}
treeQueue.add(t1.getLeft());
if (t1.getRight() == null) {
t1.attachRight(t2);
break;
}
treeQueue.add(t1.getRight());
if (!treeQueue.isEmpty()) t1 = treeQueue.remove();
else t1 = null;
}
return t1;
}