public class Test { public static void main(String[] args) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); map.put(1, 0); map.put(2, 0); map.put(3, 1); map.put(4, 1); map.put(5, 2); map.put(6, 4); map.put(7, 4); map.put(8, 7); //得到某一节点下的所有子节点(如果有) getIds(1, map); System.out.println(listRet); } private static List<Integer> listRet = new ArrayList<Integer>(); public static void getIds(int id,Map<Integer,Integer> map){ List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < map.size(); i++) { int x = map.get((i+1)); if(x==id){ list.add((i+1)); } } if(list.size()!=0){ listRet.addAll(list); System.out.println(id+"->"+list); for (int i = 0; i < list.size(); i++) { getIds(list.get(i), map); } } } }
数据库设计:
查询语句为:
SELECT * from tree WHERE position REGEXP CONCAT((SELECT position from tree where name = 'fruit'),'[\w\W]*')
当然,你用like也可以
查询结果为:
如果要插入的话略有一点复杂,步骤为:
如当我要在id=36的banana边插入一个同级的,做法为:
1、先获得blue的position,为1-1-2
2、找到1-1-2[\w\W]*匹配的正则,获取最后一段,按降序排列,得到第一个的数字
3、将数字+1,并拼装1-1-2为最终结果