需求
之前做过堆栈,优化递归实现树形结构,最近遇到一个新的需求,将树形结构转化为列表,很多情况下都是使用递归来处理,因为该方式逻辑简单,其实一般情况下如果不牵扯单io操作,多层递归也不会有什么问题,想了一下这块也可以用堆栈做一个优化,闲来无事于是实现了一下。
代码实现
Dict类
static class Dict {
public String code;
public String name;
public String parentCode;
public List<Dict> children;
public Dict(String code, String name, String parentCode) {
this(code, name, parentCode, new ArrayList<>());
}
public Dict(String code, String name,String parentCode, List<Dict> children) {
this.code = code;
this.name = name;
this.children = children;
this.parentCode = parentCode;
}
public Dict(Dict dict) {
this(dict.code, dict.name, dict.parentCode);
}
}
造数据方法
List<Dict> fakeDictData() {
List<Dict> dict = new ArrayList<>();
dict.add(new Dict("001", "编码-001", ""));
dict.add(new Dict("002", "编码-002", "",Arrays.asList(new Dict("0021", "编码-0021", "002"),
new Dict("0022", "编码-0022", "", Arrays.asList(new Dict("00221", "编码-00221", "0022"), new Dict("00222", "编码-00222", "0022"))))));
System.out.println(JSON.toJSONString(dict));
return dict;
}
递归
/**
* 树形转列表-递归
*/
@Test
public void testTree2ListRecuruly() {
List<Dict> dict = fakeDictData();
Stack<Dict> stack = new Stack<>();
dict.forEach(d -> stack.push(d));
List<Dict> newDict = new ArrayList<>();
tree2ListRecuruly(dict, newDict);
newDict.sort((d1,d2) -> d1.code.compareTo(d2.code));
System.out.println(JSON.toJSONString(newDict));
}
public void tree2ListRecuruly(List<Dict> dictTree, List<Dict> dictList) {
for(Dict d : dictTree) {
dictList.add(new Dict(d));
if(!d.children.isEmpty()) {
tree2ListRecuruly(d.children, dictList);
}
}
}
堆栈
/**
* 树形转列表-2
*/
@Test
public void tree2List2() {
List<Dict> dict = fakeDictData();
Stack<List<Dict>> stack = new Stack<>();
stack.push(dict);
List<Dict> newDict = new ArrayList<>();
while(!stack.isEmpty()) {
List<Dict> pop = stack.pop();
for(Dict d : pop) {
newDict.add(new Dict(d));
if(!d.children.isEmpty()) {
stack.push(d.children);
}
}
}
newDict.sort((d1,d2) -> d1.code.compareTo(d2.code));
System.out.println(JSON.toJSONString(newDict));
}
比较了一下,输出结果和递归的保持一致,优化完成!
标签:code,递归,List,列表,树形,dict,new,Dict,public From: https://www.cnblogs.com/bartggg/p/16644975.html