可能重复: Intersection of 2 binary trees throws Stack Overflow error Java Binary Search Trees
我需要返回一个新的OrderedSet,它包含两个二叉树的重叠元素。我认为是私有的OrderedSet抛出了这个错误,至少这是eclipse告诉我的。
private OrderedSet<E> resultIntersect = new OrderedSet<E>();
public OrderedSet<E> intersection(OrderedSet<E> other) {
OrderedSet<E> result = new OrderedSet<E>();
result = resultIntersect;
return result;
}
private void intersection(OrderedSet<E> other, TreeNode t) {
if (other.contains(t.data)) {
resultIntersect.insert(t.data);
}
if(t.left != null)
intersection(other, t.left);
if(t.right != null)
intersection(other, t.right);
}**编辑
我似乎不能让它正确地返回。如何获得正确返回结果的私有方法?
public OrderedSet<E> intersection(OrderedSet<E> other) {
OrderedSet<E> result = new OrderedSet<E>();
result = intersection(other, root, result);
return result;
}
private OrderedSet<E> intersection(OrderedSet<E> other, TreeNode t, OrderedSet<E> result) {
if (other.contains(t.data)) {
result.insert(t.data);
}
if (t.left != null && t.right != null)
return intersection(other, t.left, result) + intersection(other, t.right, result);
if (t.left != null)
intersection(other, t.left, result);
if (t.right != null)
return intersection(other, t.right, result);
else
return result;
}发布于 2012-06-30 07:51:45
我在您的other question中回答了,但是为了完整起见,它又在这里了。
虽然您没有提到它,并且您发布的代码也没有包括它,但我猜OrderedSet<E> resultIntersection是OrderedSet<E>中的一个字段。在这种情况下,当您创建OrderedSet<E>的新实例时,它会创建另一个要分配给resultIntersection的OrderedSet<E>实例。它有自己的resultIntersection,需要一个OrderedSet<E>创建实例,等等.
修复方法是删除resultIntersection并找到实现intersection的其他方法。在没有必要时,让方法通过操作共享状态来传递数据通常是不好的做法,因为这会使逻辑更难理解,并可能导致多线程问题。
https://stackoverflow.com/questions/11271544
复制相似问题