我希望用 C# 打印(到 List> 树叶的每个路径(最好是递归地)
如果是树:
A
B C
D E F G H
I
我希望得到的结果是叶子列表的列表(A是叶子,ABDI是叶子列表):
ABDI
ABE
ABF
ACG
ACH
我尝试了不同的循环,例如 foreach,但我不知道何时打印以获取整个路径。
最佳答案
您需要使用depth-first traversal 。
解决方案是:
public class Node {
public List<Node> Children {get;set;}
public string Label {get;set;}
}
public static void Print(Node node, string result)
{
if (node.Children == null || node.Children.Count == 0)
{
Console.WriteLine(result);
return;
}
foreach(var child in node.Children)
{
Print(child, result + child.Label);
}
}
这样调用它:
Print(root, root.Label);
关于c# - 递归打印树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19515798/