TreeNode(有向无环图)实现


问题内容

我需要一个像这样的树/有向无环图实现:

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; 
}
  • 没有任何种类的排序。
  • TreeNode仅仅是围绕重点和可能的值(节点不必具有值集)的包装。
  • 我需要链接到父母和孩子。

标准API或Commons等中有什么可以帮到我吗?

我不介意自己写它(我当然 也不 想问你们),我只是不想重新发明轮子。


问题答案:

似乎没有任何东西。上周,我问了一个类似的问题,并最终实现了自己的树。我的实现与您所建议的非常相似:

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

您将必须添加一个链接返回到父级。