0

重複の可能性:
2 つのバイナリ ツリーの交差によりスタック オーバーフロー エラーがスローされる
Java Binary Search Trees

2 つのバイナリ ツリーの重複する要素を含む新しい 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;
}
4

1 に答える 1

1

私はあなたの他の質問に答えましたが、完全を期すために、もう一度ここにあります。


あなたはそれについて言及しておらず、投稿されたコードにはそれが含まれていませんでしたが、OrderedSet<E> resultIntersectionは のフィールドであると推測していますOrderedSet<E>。その場合、 の新しいインスタンスを作成すると、に割り当てるOrderedSet<E>の別のインスタンスが作成されます。それには、作成のインスタンスが必要な独自のものがあります...OrderedSet<E>resultIntersectionresultIntersectionOrderedSet<E>

修正は、を削除resultIntersectionして他の実装方法を見つけることintersectionです。必要のないときに共有状態を操作してデータを渡すメソッドを持つことは、一般的に悪い習慣です。ロジックに従うのが難しくなり、マルチスレッドの問題が発生する可能性があるためです。

于 2012-06-30T07:51:45.330 に答える