2013-10-22 132 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); 
    } 
} 

這樣稱呼它遞歸地使用