-1

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

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

1 回答 1

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

但这不是很通用的。你能详细说明你的需求吗?

于 2012-08-06T04:42:48.167 回答