Java树数据结构实现

时间:2016-12-06 16:06:55

标签: java algorithm tree

有人能指出我在Java中标准,经过测试的简单树实现吗?

例如,Java Tree上的所有StackOverflow搜索都会导致此主题, Tree implementation in Java (root, parents and children)

然后你发现该主题中的接受答案不起作用并给出溢出异常(https://stackoverflow.com/a/40622616/1005607) - 非常危险,也许有人应删除或编辑该答案或至少移动它下来。

有一些非StackOverflow资源,但我再也不知道它们有多可靠, http://programtalk.com/java/java-tree-implementation/

我发现很难相信我们可以快速实现可重用的强大实施。节点应跟踪其父节点和子节点。应该没有错误。

1 个答案:

答案 0 :(得分:2)

您展示的问题(https://stackoverflow.com/a/40622616/1005607)的问题是方法addChildsetParent在无限循环中相互调用。

public void setParent(Node<T> parent) {
    parent.addChild(this);  // Call addChild
    this.parent = parent;
}

public void addChild(Node<T> child) {
    child.setParent(this);   // Call setParent
    this.children.add(child);
}

您需要修改如下:

// Make this method private
private void setParent(Node<T> parent) {
    // Remove this line to prevent the loop
    // parent.addChild(this);
    this.parent = parent;
}

public void addChild(Node<T> child) {
    child.setParent(this);
    this.children.add(child);
}
相关问题