多叉树的深度优先遍历并输出叶子路径

 在做项目的过程中,遇到了多叉树的访问问题,其中要求保存访问至叶子节点的路径,查找网上资料都不是很合心意,故而自己用比较笨的方法保存然后输出

多叉树结构:

class DataModel
    {
        public string name { get; set; }
        public List children { get; set; } = new List();
    }

递归深度遍历多叉树,并保存路径

public static List paths = new List(); //定义保存路径的数组
public static void FindAllPaths(DataModel treeNodes, string path)
        {
            path += treeNodes.name + "->";
            if (treeNodes == null
                || treeNodes.children.Count == 0)
            {
                string leafPath = path;
                paths.Add(leafPath);
                return;
            }

            for (int i = 0, len = treeNodes.children.Count; i < len; i++)
            {
                FindAllPaths(treeNodes.children[i], path);
            }
        }
	//函数调用:
 	string path = string.Empty;
	FindAllPaths(node1, path);

 
 

你可能感兴趣的:(C#,算法)