@Override public List<Tree> queryAllTreeNode(){ return treeMapper.queryAllTreeNode(); }
//寻找父节点 private List<Tree> findFather(List<Tree> trees){ List<Tree> father = new ArrayList<>(); for (Tree tree : trees){ if (tree.getPid() == null){ father.add(tree); } } return father; }
//寻找该父节点的子节点 private List<Tree> findChild(Tree tree, List<Tree> trees){ List<Tree> child = new ArrayList<>(); for (Tree t : trees){ if (tree.getId().equals(t.getPid())){ child.add(t); } } return child; }
//递归关联一个父节点下的所有子节点 private List<Tree2> addTree(Tree tree, List<Tree> trees){ List<Tree> childs = findChild(tree, trees); List<Tree2> nodes = new ArrayList<>(); if (childs != null){//子节点存在 for (Tree c : childs){ if (c.getPid().equals(tree.getId())){ Tree2 node = new Tree2(c.getId(), c.getName(), addTree(c, trees)); //将Tree类型数据转变为Tree2类型,并递归寻找自己的子节点 nodes.add(node); //将Tree2类型数据添加到列表中 } } } return nodes; }
//递归关联父节点与子节点 public List<Tree2> treeNodes(){ List<Tree> trees = queryAllTreeNode(); List<Tree> father = findFather(trees); List<Tree2> nodes = new ArrayList<>();
for (Tree f : father){ Tree2 node = new Tree2(f.getId(), f.getName(), addTree(f, trees)); //递归寻找自己的子节点,并变成Tree2类型数据 nodes.add(node); } return nodes; } }