【问题标题】:Java Tree Data Structure Implementation [closed]Java树数据结构实现[关闭]
【发布时间】:2016-12-06 16:06:55
【问题描述】:

有人可以指出Java 中标准、经过测试、简单的 Tree 实现吗?

例如,Java 树上的所有 StackOverflow 搜索都指向这个主题, Tree implementation in Java (root, parents and children)

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

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

我很难相信没有可以快速实现的可重用健壮实现。该节点应跟踪其父级和子级。应该没有错误。

【问题讨论】:

  • 我使用了 Mark Allen Weiss 在 Java 中的数据结构和算法分析,在树部分有一个很好的树实现

标签: java algorithm tree


【解决方案1】:

您展示的问题(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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    相关资源
    最近更新 更多