gpt4 book ai didi

java - 相交 2 个二叉树 - 抛出堆栈溢出错误

转载 作者:行者123 更新时间:2023-12-01 15:18:44 24 4
gpt4 key购买 nike

Possible Duplicate:
Intersection of 2 binary trees throws Stack Overflow error
Java Binary Search Trees

我需要返回一个新的 OrderedSet,其中包含两个二叉树的重叠元素。我认为是私有(private) 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);
}

**编辑

我似乎无法让它正确返回。如何让私有(private)方法正确返回结果?

    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;
}

最佳答案

我在你的other question中回答了,但为了完整起见,这里又是这样。

<小时/>

虽然你没有提到它,而且你发布的代码也没有包含它,但我猜 OrderedSet<E> resultIntersectionOrderedSet<E> 中的一个字段。在这种情况下,当您创建 OrderedSet<E> 的新实例时它创建 OrderedSet<E> 的另一个实例分配给resultIntersection 。那么它就有它自己的resultIntersection需要 OrderedSet<E> 的实例创建等等...

修复方法是删除 resultIntersection并找到其他一些实现方式 intersection 。在不必要时让方法通过操作共享状态来传递数据通常是不好的做法,因为这会使逻辑更难以遵循,并可能导致多线程问题。

关于java - 相交 2 个二叉树 - 抛出堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11271544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com