最近遇到一个业务需求:一颗依赖树,其实就是一颗递归树,如何一层一层的数据放在一起,可以近似理解为二叉树的层序遍历。
业务理解为递归树的层序遍历
代码示例:
public class RecursionErgodic {public static void main(String[] args) {User user = buildUser();System.out.println(user);Map<Integer, List<String>> map = new HashMap<>();int index = 1;List<User> childRen = user.getChildRen();List<String> list = new ArrayList<>();list.add(user.getName());map.put(index, list);cfsTraversal(childRen, map, index + 1);System.out.println(map);}private static void cfsTraversal(List<User> childRen, Map<Integer, List<String>> map, int index) {if (childRen == null) {return;}int size = childRen.size();for (int i = 0; i < size; i++) {User user = childRen.get(i);List<String> list = map.get(index);if (list == null) {list = new ArrayList<>();}list.add(user.getName());map.put(index, list);//特别注意:递归 这里不要改变index本身的值cfsTraversal(user.getChildRen(), map, index + 1);}}public static User buildUser() {User user = new User();user.setId(1);user.setName("座山雕");User user1 = new User();user1.setId(2);user1.setName("刘大脑袋");User user2 = new User();user2.setId(3);user2.setName("殷八字");User user3 = new User();user3.setId(4);user3.setName("刘大脑袋徒弟1");User user4 = new User();user4.setId(5);user4.setName("刘大脑袋徒弟2");User user5 = new User();user5.setId(6);user5.setName("殷八字徒弟2");List<User> list2 = new ArrayList<>();list2.add(user4);list2.add(user3);user1.setChildRen(list2);List<User> list3 = new ArrayList<>();list3.add(user5);user2.setChildRen(list3);List<User> list1 = new ArrayList<>();list1.add(user1);list1.add(user2);user.setChildRen(list1);return user;}static class User {private int id;private String name;private List<User> childRen;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public List<User> getChildRen() {return childRen;}public void setChildRen(List<User> childRen) {this.childRen = childRen;}}
}
结果:
输入(一个对象):
{"childRen":[{"childRen":[{"id":5,"name":"刘大脑袋徒弟2"},{"id":4,"name":"刘大脑袋徒弟1"}],"id":2,"name":"刘大脑袋"},{"childRen":[{"id":6,"name":"殷八字徒弟2"}],"id":3,"name":"殷八字"}],"id":1,"name":"座山雕"}
输出(一个map)
{1=[座山雕], 2=[刘大脑袋, 殷八字], 3=[刘大脑袋徒弟2, 刘大脑袋徒弟1, 殷八字徒弟2]}