我目前正在实施二进制搜索树,并坚持将其与另一个进行合并。 到目前为止我已经:
由于我收到了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;
}
答案 0 :(得分:0)
public BinaryTree merge(BinaryTree other) {
if (other != null) {
return insert(other.head()).merge(other.tail());
}
return this;
}
/**
* Get the tail of a tree.
* @return the tree without the smallest value.
*/
public BinaryTree tail() {
if (left != null) {
return new BinaryTree(value, left.tail(), right);
}
return right; // Could make a deep copy.
}