2013-10-22 130 views
2

我想打印(列出>用C#(最好是递归)打印树递归

在树的情况下树叶的每个路径:

   A 
     B   C 
     D E F  G H 
    I 

结果我希望得到的是列表叶清单(A为叶,阿卜迪是叶子的列表):

ABDI 
ABE 
ABF 
ACG 
ACH 

我尝试不同的环路一样的foreach,但我不知道何时打印让整个路径

。 10

回答

3

您需要使用depth-first traversal

解决办法是:使用堆栈,这样做的另一块干净的方式,

push (root); 
while (top()) 
{ 
    pop (top); 
    push (node->right); 
    push (node->left); 
} 

可以做到这一点

Print(root, root.Label); 
0

应该是这样的:(第一次调用ListNodes(node,“”);

private void ListNodes(TreeNode node, string root) 
{ 
    if (node.Nodes.Count > 0) 
    { 
     foreach (TreeNode n in node.Nodes) 
     { 
      ListNodes(n, root + node.Text); 
     } 
    } 
    else 
    { 
     Console.Write(" " + root + node.Text); 
    } 
} 
+0

使用Console.WriteLine以获得预期结果 – dave

0

说你有一个这样的结构:

void PrintPaths (Node node, List<Node> currentPath) 
{ 
    currentPath = new List<Node>(currentPath); 
    currentPath.Add (node); 
    if (node.Children.Any()) { 
     foreach (var child in node.Children) 
      PrintPaths (child, currentPath); 
    } else { 
     //we are at a leaf, print 
     foreach (var n in currentPath) 
      Console.Write (n.Label); 
     Console.WriteLine(); 
    } 
} 

称此为根节点:PrintPaths (rootnode, null);

class Node { 
    List<Node> Children {get;set;} 
    string Label {get;set;} 
} 

您就可以使用递归方法打印路径

如果您想要返回这些列表而不是打印,请传递额外的参数,将List<List<Node>>添加到方法中,而不是在最后打印,请将当前路径添加到结果中。

var result = new List<List<Node>>(); 

GetPaths (rootNode, null, result); //implementation not provided, but trivial 
+0

这将打印ABDI ABDIE ABDIEF ....它将叶添加到路径中,但仍旧记住旧路。 – santBart

+0

哦,对,让我解决这个问题。 –

+0

应该修复。该列表不再共享。我直接在S.O上输入这个代码。而不尝试编译或执行。 –

0

深度优先搜索:

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); 
    } 
} 

这样称呼它递归地使用