日期:2014-05-20  浏览次数:20701 次

高分求救查询树形结构中某节点逆展开所有路径问题
比如有一个表结构 

id    parent    child 
A     1         3 
B     2         3 
C     3         4 
D     5         4 
E     6         4 
F     7         5 
G     8         4 

如何取得所有root节点到节点4的所有路径的id 
放到map中,key为parent,value为list<id> 

如上表应该有5条路径 

1)     1 > 3 > 4    map.put(1 : C,A)
2)     2 > 3 > 4    map.put(2 : C,B)
3)     7 > 5 > 4    map.put(7 : F,D)
4)     6 > 4        map.put(6 : E)
5)     8 > 4        map.put(8 : G)

请大家帮忙解决一下,谢谢了。。。
------最佳解决方案--------------------
Map<Integer, List<String>> result = new HashMap<Integer, List<String>>();
Map<Integer, Integer> temp1 = new HashMap<Integer, Integer>();
temp1.put(1, 3);
temp1.put(2, 3);
temp1.put(3, 4);
temp1.put(5, 4);
temp1.put(6, 4);
temp1.put(7, 5);
temp1.put(8, 4);
Map<Integer, Integer> temp2 = new HashMap<Integer, Integer>();
temp2.put(3, 1);
temp2.put(3, 2);
temp2.put(4, 3);
temp2.put(4, 5);
temp2.put(4, 6);
temp2.put(5, 7);
temp2.put(4, 8);
Map<Integer, String> temp3 = new HashMap<Integer, String>();
temp3.put(1, "A");
temp3.put(2, "B");
temp3.put(3, "C");
temp3.put(5, "D");
temp3.put(6, "E");
temp3.put(7, "F");
temp3.put(8, "G");
Iterator<Integer> it = temp1.keySet().iterator();
while (it.hasNext()) {
Integer pid = it.next();
if (!temp2.containsKey(pid)) {
List<String> list = new ArrayList<String>();
result.put(pid, list);
list.add(temp3.get(pid));
Integer id = temp1.get(pid);
while (temp1.containsKey(id)) {
list.add(temp3.get(id));
id = temp1.get(id);
}
}
}
System.out.println(result);
result:{2=[B, C], 8=[G], 6=[E], 1=[A, C], 7=[F, D]}
为啥结果会不同?
------其他解决方案--------------------
这种存储方式就是一个简单的链接表存储图的顶点和边,当然可以使用图搜索算法。
但是由于问题的简单性,可以直接使用深度搜索到目标的路径。
package com.tur.demo;

import java.util.*;

public class Hello {
    public static void main(String[] args) {
        /*
        id    parent    next
        A     1         3