1
我目前正在實現一個二叉搜索樹,並被困在合併與另一個。 到目前爲止,我已經有了:通過插入合併2個二叉搜索樹
- 頭:用最小的節點返回節點
- 尾:返回樹W/O最小節點
- 插入(值):傳統的插入法
由於我得到一個StackOverflowError,我認爲最好是提供所有方法,而不僅僅是合併。我很確定這個錯誤在某種程度上是由於遞歸調用的數量。
我很感激任何幫助! TYVM。
public BinaryTree insert(int newValue) {
if (newValue < value) {
if (left == null) {
return new BinaryTree(value, new BinaryTree(newValue), right);
} else {
return new BinaryTree(value, left.insert(newValue), right);
}
} else if (newValue > value) {
if (right == null) {
return new BinaryTree(value, left, new BinaryTree(newValue));
} else {
return new BinaryTree(value, left, right.insert(newValue));
}
}
return this;
}
public int head() {
if (left != null) {
return left.head();
}
return value;
}
public BinaryTree tail() {
if (left != null) {
return new BinaryTree(value, left.tail(), right);
} else {
return new BinaryTree(value, left, right.tail());
}
}
public BinaryTree merge(BinaryTree other) {
if (other != null) {
insert(other.head()merge(other.tail()));
}
return this;
}
嘿,感謝您的答覆。但它仍然給我StackOverflowError。我認爲問題在於tail()。如果我能以某種方式讓tail()工作,而不必使用head(),那麼它可能會運行。 :-( – mowtheone
我已經添加了邏輯尾部實現_(總是最後實現的方法顯然會搞砸了。)_ –