如何导航具有List元素的List树

时间:2017-04-25 19:01:17

标签: c# list data-structures tree

基本上,我需要迭代许多列表中的每个列表。金额没有给出,所以我猜必须使用递归,但是我们的赋值没有类似递归的方法,所以我现在处于亏损状态。 PS。代码与我的代码相同,但我可能没有正确翻译,所以请注意方法。

编辑:程序的作用 - 你可以创建状态 - 然后将子状态添加到状态,然后子状态到子状态等等。

 class Tree
{
    public List<Branch> Branches;
    public void Print()
    {
        foreach (Branch item in Branches)
        {

        }
    }
class Branch
{
    public State state;
    public List<Branch> branch;
}
class State
{
    public string name;
    public string size;
}

1 个答案:

答案 0 :(得分:1)

您可能想要做的是创建一些printRecursive(分支分支)方法,然后在Print()中的空foreach中迭代它。我假设没有子分支的分支只有一个空列表。该方法可能类似于:

printRecursive(Branch branch) {
    printState(branch.state); 
    foreach(Branch b in branch.branch) {
        printRecursive(b); 
    }
}

printState(State state) {
    Console.WriteLine("State: " + state.name + ". Size: " + state.size); 
}

编辑:

如果在每次迭代中创建树,则甚至不需要这些额外的方法。这似乎是一种不切实际的方法,但如果你不能制作任何新的方法,我看不到另一种选择。只需让你的Print()看起来像:

void Print() {
    foreach (Branch b in Branches) {
        // print b.state here 
        Tree tree = new Tree(); 
        tree.Branches = b.branch;
        tree.Print(); 
     }
 }