是否可以从列表中构建树?

时间:2015-06-27 09:18:32

标签: c# algorithm

我有这个数据结构:

public class Node
{
    public String Name {get; set;}
    public List<Link> Links {get; set;} 
}

public class Link
{
    public int Id {get; set;}
}

数据可能包括:

Node    Links
--------------------
A       1
B       2, 3
C       4, 5
D       6

A是起始节点,D是结束节点。中间的节点处于固定顺序。结果应该是从A到D的“路径”列表,它将是:

A1->B2->C4->D6
A1->B2->C5->D6
A1->B3->C4->D6
A1->B3->C5->D6

可以使用哪种算法来获得上述结果?

1 个答案:

答案 0 :(得分:2)

看看这个递归实现:

using System;

public class Node {
    public String Name {get; set;}
    public int[] Links {get; set;} 
}

public class Program
{
    private static Node[] nodes = new[] {
        new Node { Name = "A", Links = new[] { 1 } },
        new Node { Name = "B", Links = new[] { 2, 3 } },
        new Node { Name = "C", Links = new[] { 4, 5 } },
        new Node { Name = "D", Links = new[] { 6 } }
    };

    private static void PrintPath(int depth, string path)
    {
        if (depth == nodes.Length) 
        {
            Console.WriteLine(path);
        }
        else 
        {
            foreach(var link in nodes[depth].Links)
            {
                PrintPath(
                    depth+1, 
                    string.Format("{0}{1}{2} ", path, nodes[depth].Name, link));
            }
        }
    }

    public static void Main()
    {
        PrintPath(0, string.Empty);
    }
} 

为了简单起见,我已将Link类替换为int并使用数组而不是列表,但您应该明白这一点。