java递归生成树形结构_java树形结构如何用递归实现?

public class Ttt {

public String tree(List ret, String rootId, String p) {

StringBuffer retList = new StringBuffer();

for (Map m : ret) {

if (rootId.equals(m.get("PARENTID"))) {

retList.append(p+m.get("NAME")+"\n");

retList.append(tree(ret, (String) m.get("ID"), p + "-"));

}

}

return retList.toString();

}

public static void main(String[] args) {

List list = new ArrayList<>();

Map m = new HashMap<>();

m.put("ID", "1");

m.put("NAME", "a");

m.put("PARENTID", "root");

list.add(m);

m = new HashMap<>();

m.put("ID", "2");

m.put("NAME", "b");

m.put("PARENTID", "1");

list.add(m);

m = new HashMap<>();

m.put("ID", "3");

m.put("NAME", "c");

m.put("PARENTID", "2");

list.add(m);

m = new HashMap<>();

m.put("ID", "4");

m.put("NAME", "d");

m.put("PARENTID", "1");

list.add(m);

m = new HashMap<>();

m.put("ID", "5");

m.put("NAME", "e");

m.put("PARENTID", "root");

list.add(m);

m = new HashMap<>();

m.put("ID", "6");

m.put("NAME", "f");

m.put("PARENTID", "5");

list.add(m);

m = new HashMap<>();

m.put("ID", "7");

m.put("NAME", "g");

m.put("PARENTID", "2");

list.add(m);

m = new HashMap<>();

m.put("ID", "8");

m.put("NAME", "h");

m.put("PARENTID", "2");

list.add(m);

m = new HashMap<>();

m.put("ID", "9");

m.put("NAME", "i");

m.put("PARENTID", "3");

list.add(m);

Ttt t = new Ttt();

System.out.println(t.tree(list, "root", ""));

}

}

运行效果

5f44669d9023f819b9cfa4031178418d.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值