如何从给定的父节点获取所有子节点?

Mar*_*cus 4 .net c# algorithm recursion relationship

我有一个父/子ID列表,并希望获得给定父ID的所有子ID.没有空父项(顶级ID不显示为子ID).

目前,父/子ID在列表中记录为KeyValuePair,但是如果更好的话,可以很容易地将其更改为另一个数据结构:

List<KeyValuePair<int, int>> groups = new List<KeyValuePair<int, int>>();
groups.Add(new KeyValuePair<int,int>(parentID, childID));
Run Code Online (Sandbox Code Playgroud)

例如,以下是示例父/子.父母27的孩子将是5944,2065,2066,2067,6248,6249,6250.

Parent  Child
27      1888
1888    5943
1888    5944
5943    2064
5943    2065
5943    2066
5943    2067
2064    6248
2064    6249
2064    6250
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

Blu*_*rry 5

为什么不改变Dictionary<int, List<int>>父类型的类型,其中的值(整数列表)是孩子?

然后你将使用以下命令返回子项列表:

    private List<int> GetAllChildren(int parent)
    {
        List<int> children = new List<int>();
        PopulateChildren(parent, children);
        return children;
    }

    private void PopulateChildren(int parent, List<int> children)
    {
        List<int> myChildren;
        if (myitems.TryGetValue(parent, out myChildren))
        {
            children.AddRange(myChildren);
            foreach (int child in myChildren)
            {
                PopulateChildren(child, children);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

您将需要权衡性能影响,因为这将加快读取速度并减慢写入速度(绝大多数时间没有人会注意到).

您还需要检查列表是否在字典中myitems.TryGet(...),如果没有,您将需要创建它,但这是o(1),所以几乎是即时的.

private static void AddEntry(int parent, int child)
{
    List<int> children;
    if (!myitems.TryGetValue(parent, out children))
    {
        children = new List<int>();
        myitems[parent] = children;
    }
    children.Add(child);
}
Run Code Online (Sandbox Code Playgroud)