如何使用此数据结构构建树

时间:2012-08-06 04:15:06

标签: c# recursion tree

我有这种树结构,一个节点可能有多个节点。

public class Node
{
    public Node()
    {
        ChildLocations = new HashSet<Node>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual int? ParentLocationId { get; set; }
    public virtual ICollection<Node> ChildLocations { get; set; }
}

现在,我想在此结构中添加parent-child值列表。像:

{1,A} -> {2,B}
{1,A} -> {3,C}
{1,A} -> {4,D}
{3,C} -> {5,E}
{3,C} -> {6,F}
构建树的

如下所示:

          1A
        / |  \
    2B    3C   4D
         / \ 
       5E   6F

最后,它返回root引用。

我已经提出了这个解决方案。但我对递归部分没有信心。这是正确的吗?

public class Tree
{
    Node root;

    public Node Root
    {
        get { return root; }
    }

    public void Add(int parentId, string parentName, int childId, string childName)
    {
        if (root == null)
        {
            root = new Node { Id = parentId, Name = parentName };
            root.ChildLocations.Add(new Node { Id = childId, Name = childName });
        }
        else
        {
            Add(root, parentId, parentName, childId, childName);
        }
    }

    private void Add(Node node, int parentId, string parentName, int childId, string childName)
    {
        if (node == null)
        {
            return;
        }
        if (node.Id == parentId)
        {
            node.ChildLocations.Add(new Node { Id = childId, Name = childName });
            return;
        }
        foreach (var n in node.ChildLocations)
        {
            Add(n, parentId, parentName, childId, childName);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

根据我对您的问题的评论,这可以构建您需要的树:

public Node BuildTree()
{
    var _1A = new Node() { Id = 1, Name = "A", };
    var _2B = new Node() { Id = 2, Name = "B", };
    var _3C = new Node() { Id = 3, Name = "C", };
    var _4D = new Node() { Id = 4, Name = "D", };
    var _5E = new Node() { Id = 5, Name = "E", };
    var _6F = new Node() { Id = 6, Name = "F", };
    _1A.ChildLocations.Add(_2B);
    _1A.ChildLocations.Add(_3C);
    _1A.ChildLocations.Add(_4D);
    _3C.ChildLocations.Add(_5E);
    _3C.ChildLocations.Add(_6F);
    return _1A;
}

但这不是很普遍的目的。你能详细说明你的需求吗?