递归函数的写法笔记

脑袋总是记不住,做个笔记记下方便用时查询。

 

情景一:Java电商项目中的商品品类管理。品类呈树形结构,现要求找到某一节点下的所有子节点。

// 递归算法,找到子节点
private Set<Category> findChildCategory(Set<Category> categorySet, Integer categoryId){
    // Mybatis的数据库查询方法
    Category category = categoryMapper.selectByPrimaryKey(categoryId);
    if (category != null){
        categorySet.add(category);
    }

    // 查找子节点,如果子节点为空就退出递归。递归算法一定要有一个退出的条件
    List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
    for (Category categoryItem : categoryList){
        findChildCategory(categorySet, categoryItem.getId());
    }

    return categorySet;
}

这里为了防止品类重复使用了Set集合。使用该集合要求实体类Category重写equals()和hashCode()方法。

 

情景二:WPF中UI呈树形结构,想要查找指定控件下的所有子控件。

public static List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement
{
    DependencyObject child = null;
    List<T> childList = new List<T>();

    for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
    {
        child = VisualTreeHelper.GetChild(obj, i);

        if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
        {
            childList.Add((T)child);
        }

        childList.AddRange(GetChildObjects<T>(child, ""));
    }

    return childList;
}

 

观察函数的规律:

  • 返回值和传参是相同的集合列表。
  • 传参一个变量用来筛选符合条件的子节点。

 

获取文件下所有层级的文件

public static List<string> GetAllFiles(DirectoryInfo dir)
{
    FileInfo[] fileInfos = dir.GetFiles();
    foreach (FileInfo fi in fileInfos)
    {
        FileList.Add(fi.Name);
    }
    DirectoryInfo[] dirInfos = dir.GetDirectories();
    foreach (DirectoryInfo d in dirInfos)
    {
        GetAllFiles(d);
    }
    return FileList;
}

 

posted @ 2018-01-10 09:52  霍莉雪特  阅读(216)  评论(0编辑  收藏  举报