树的路径查找算法
问题:对于树中的某个节点,找到他在树中的路径。比如如下图中Z的path为{0, 1, 3, 1}。
最原始的DFS算法为:
private static void getPath(List<Entry> list, ID id, ArrayList<Integer> matchPath,
int... path) {
for (int i = 0; i < list.size(); i++) {
int length = path.length;
int[] currentPath = new int[length + 1];
System.arraycopy(path, 0, currentPath, 0, length);
currentPath[length] = i;
Entry entry = list.get(i);
if (id.equals(entry.id)) {
if (matchPath.size() == 0) {
for (int j : currentPath) {// clone
matchPath.add(j);
}
}
} else
getPath(entry.getChildren(), id, matchPath, currentPath);
}
}
但是这种算法虽然完成了任务,但总觉得过于罗嗦。写好后三个月,又摸回去改了改,结果如下,使用了Stack来和DFS互动。
private static void getPath(List<Entry> list, ID id, Stack<Integer> path, Flag isFound) {
for (int i = 0; i < list.size() && !isFound.value; i++) {
Entry entry = list.get(i);
path.push(i);
if (id.equals(entry.id)) {
isFound.value = true;
return;
} else{
getPath(entry.getChildren(), id, path, isFound);
}
}
if(isFound.value)
return;
if ( !path.empty())
path.pop();
}
简单的才是对的,要有这种信念。做人就得信,做….