1

我做了很多搜索,但现有的解决方案都没有解决我的确切问题。我有一个清单:

Input[] inputs = new Input[]
{
    new Input(1),
    new Input(3,1),
    new Input(19,3),
    new Input(22,1),
    new Input(4,1),
    new Input(5,22),
};

下面是 BuildTree() 的声明,它目前不起作用:

public TreeNode BuildTree(IEnumerable<Input> inputs, TreeNode parentNode = null)
{
    List<Input> nodes = inputs.ToList<Input>();

    foreach (Input node in nodes)
    {
        TreeNode newNode = new TreeNode(node.Id);
        if (parentNode == null)
        {
            parentNode = BuildTree(nodes, newNode);
        }
        else
        {
            parentNode.AddChild(newNode);
        }
    }

    return parentNode;
}

这是对 BuildTree 的调用:

TreeNode rootNode = BuildTree(inputs);

所以 BuildTree 函数必须在构建后返回树的根。我试过循环输入。我尝试在每次迭代时从列表中删除第一个输入。我不太明白。任何帮助将不胜感激!谢谢!

4

1 回答 1

1

您不需要递归,因为您正在将列表转换为树,而不是将树转换为列表。

由于您的输入列表不是标准的树遍历,并且您没有告诉我们父节点是否总是在子节点之前,我们可以使用的最简单的方法是Dictionary.

public TreeNode BuildTree(IEnumerable<Input> inputs)
{
    TreeNode rootNode = null;
    // Build a dictionary to store each input and its node
    var dict = inputs.ToDictionary(
        input => input.Id,
        input => new { Input = input, Node = new TreeNode(input.Id.ToString()) });

    // Iterate through the nodes and build relationship among them
    foreach(var value in dict.Values)
    {
        var input = value.Input;
        if(input.ParentId != null)
        {
            dict[(int)input.ParentId].Node.Nodes.Add(value.Node);
        }
        else
        {
            rootNode = value.Node;
        }
    }
    return rootNode;
}
于 2013-11-14T06:09:52.733 回答