C# 递归打印树
我希望打印(列出>带有c#的每个树叶路径)(最好是递归) 如果是树:C# 递归打印树,c#,list,data-structures,tree,C#,List,Data Structures,Tree,我希望打印(列出>带有c#的每个树叶路径)(最好是递归) 如果是树: A B C D E F G H I 我希望得到的结果是叶子列表(A是叶子,ABDI是叶子列表): 我尝试了不同的循环,比如foreach,但我不知道什么时候打印以获得整个路径。应该是这样的:(调用第一次ListNodes(节点“”) 假设你有这样一个结构: class Node { List<Node>
A
B C
D E F G H
I
我希望得到的结果是叶子列表(A是叶子,ABDI是叶子列表):
我尝试了不同的循环,比如foreach,但我不知道什么时候打印以获得整个路径。应该是这样的:(调用第一次ListNodes(节点“”)
假设你有这样一个结构:
class Node {
List<Node> Children {get;set;}
string Label {get;set;}
}
Print(root, root.Label);
你需要使用
解决办法是:
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);
}
}
使用堆栈进行深度优先搜索,这是另一种干净的方法
push (root);
while (top ())
{
pop (top);
push (node->right);
push (node->left);
}
这可以递归完成使用Console.WriteLine获得预期结果这会打印ABDI ABDI ABDIE ABDIEF…它会将叶添加到路径中,但仍然记住旧路径。应该修复。列表不再共享。我在S.O.上直接键入此代码,而不尝试编译或执行。
var result = new List<List<Node>> ();
GetPaths (rootNode, null, result); //implementation not provided, but trivial
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);
push (root);
while (top ())
{
pop (top);
push (node->right);
push (node->left);
}