简体   繁体   English

树(有向无环图)实现

[英]Tree (directed acyclic graph) implementation

I require a tree / directed acyclic graph implementation something like this: 我需要一个树/有向无环图实现,如下所示:

public class TreeNode<K, V> {
    private K key; // 'key' for this node, always present
    private V value; // 'value' for this node, doesn't have to be set

    private TreeNode<K, V> parent;
    private Set<TreeNode<K, V>> children; 
}
  • There is no sorting of any kind. 没有任何类型的分类。
  • The TreeNode is just a wrapper around the key and a possible value (nodes don't have to have values set). TreeNode只是键的包装和可能的值(节点不必设置值)。
  • I require links to both the parent and the children. 我需要父母和子女的链接。

Is there anything out there in the standard APIs or Commons etc that will do this for me? 标准API或Commons等中有什么东西可以帮我吗?

I don't mind writing it myself (and I'm certainly not asking you folks to) I just don't want to re-invent the wheel. 我不介意自己写(我当然不是要求大家)我只是不想重新发明轮子。

There doesn't seem to be anything of the kind. 似乎没有任何类似的东西。 I asked a similar question last week and ended up implementing my own tree. 上周我问了一个类似的问题,最后实现了我自己的树。 My implementation was very similar to what you're proposing: 我的实现非常类似于你提出的建议:

public class TreeNode<T>
{
    private LinkedList<TreeNode<T>> children = new LinkedList<TreeNode<T>>();
    public T value { get; set; }

    public TreeNode(T value)
    {
        this.value = value;
    }
    public LinkedList<TreeNode<T>> GetChildren()
    {
        return children;
    }
}

You will have to add a link back to the parent(s). 您必须将链接添加回父级。

There's also http://www.jgrapht.org , which has software licensed under the LGPL. 还有http://www.jgrapht.org ,其中包含根据LGPL许可的软件。 I have to warn you though, implementing your own is fraught with danger. 我必须警告你,实施你自己的工作充满了危险。 If you plan on using recursion on your structure (which is a graph), you'll have to ensure that it's acyclic, or you'll run into infinite loop problems. 如果您打算在结构上使用递归(这是一个图形),您必须确保它是非循环的,否则您将遇到无限循环问题。 Better to use third party code where they've already dealt with the issues. 最好在他们已经处理过这些问题的地方使用第三方代码。

I'd say it's better to roll out your own implementation (besides, you've already got the interface nicely thought out). 我说最好推出自己的实现(此外,你已经很好地考虑了界面)。 What are the operations you are planning to perform on this tree anyway? 无论如何,您计划在此树上执行​​哪些操作? You'd probably want to design your API around the things you want... direct access to individual nodes by key/value? 你可能想围绕你想要的东西设计你的API ...按键/值直接访问各个节点? types of traversals? 遍历的类型? add/remove operations? 添加/删除操作?

如果您正在寻找额外的图形功能, JDigraph有向图类应符合要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM