递归打印树

本文关键字:打印 递归 | 更新日期: 2023-09-27 18:36:19

我希望用c#打印(到列表>树叶的每个路径(最好是递归的)

如果是树:

               A
         B           C
      D  E  F       G  H
    I
我希望得到的结果是叶子列表(A是叶子

,ABDI是叶子列表):

ABDI
ABE
ABF
ACG
ACH

我正在尝试不同的循环,例如foreach,但我不知道何时打印以获得整个路径。

递归打印树

您需要使用深度优先遍历。

解决方案是:

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

应该是这样的:(第一次调用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);
    }
}

假设你有一个这样的结构:

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

您可以使用递归方法打印路径,如下所示:

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

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

var result = new List<List<Node>> ();
GetPaths (rootNode, null, result); //implementation not provided, but trivial

深度优先 使用堆栈进行搜索,这是另一种干净的方法

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

这可以递归完成