首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >交叉2棵二叉树-抛出堆栈溢出错误

交叉2棵二叉树-抛出堆栈溢出错误
EN

Stack Overflow用户
提问于 2012-06-30 04:57:11
回答 1查看 282关注 0票数 0

可能重复: Intersection of 2 binary trees throws Stack Overflow error Java Binary Search Trees

我需要返回一个新的OrderedSet,它包含两个二叉树的重叠元素。我认为是私有的OrderedSet抛出了这个错误,至少这是eclipse告诉我的。

代码语言:javascript
运行
复制
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);
}

**编辑

我似乎不能让它正确地返回。如何获得正确返回结果的私有方法?

代码语言:javascript
运行
复制
    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;
}
EN

回答 1

Stack Overflow用户

发布于 2012-06-30 07:51:45

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

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11271544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档