递归算法代码实例
1 //获取数据方法 2 public List<TreeVo> tree(List<ListVo> list, String id, String state, 3 String[] str, GetTreeVoInterface getTree) { 4 ArrayList<TreeVo> listTree = new ArrayList<TreeVo>(); 5 //遍历原始数据 6 for (int i = list.size(); i > 0; i--) { 7 ListVo vo = list.get(i - 1); 8 String pid = vo.getPid(); 9 //清除已处理数据 10 if (check(pid, id)) { 11 list.remove(vo); 12 TreeVo tree = getTree.getTreeVo(vo, str); 13 listTree.add(tree); 14 } 15 } 16 17 // 遍历子节点 18 for (TreeVo tree : listTree) { 19 //判断是否有数据,没有数据返回上一级 20 if (tree.getId() != null) { 21 22 String id2 = tree.getId(); 23 int lastIndexOf = id2.lastIndexOf('/'); 24 String substring = id2.substring(lastIndexOf+1); 25 //运用递归 26 //难点在于递归应用的地方以及递归的返回数据 27 //如果递归无终止条件,程序将会运行为死循环,无限循环,最终程序会跑死 28 List<TreeVo> listTreeChildren = tree(list, substring, state, 29 str, getTree); 30 tree.setChildren(listTreeChildren); 31 } 32 } 33 return listTree; 34 }