我使用以下方法(使用广度优先遍历算法)以连续顺序将项目添加到二叉树中。
例如,如果我有
A
/ \
B C
/
D
我希望下一个补充是:
A
/ \
B C
/ \
D E
我的问题在于我不确定如何正确返回值。我知道当我们遇到第一个空节点时,我们会在其中插入值,但是我们将它插入到什么地方呢?如果我们将它插入到我们从队列中获取的二叉树中,那是根的子树(或我们试图添加到的树),所以返回它不会是完整的树。
这是我的代码:
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;
}