我试图以dfs的顺序迭代地遍历图表 以下是我的代码。 当我测试它时,输出与递归dfs的输出不同(也包括在下面)。
有人可以帮忙调试吗?
public static void dfs(GraphNode root) {
if (root != null && !root.visited) {
for (GraphNode kid : root.children) {
dfs(kid);
}
System.out.println(root);
root.visited = true;
}
}
public static void dfsIter(GraphNode root) {
Stack<GraphNode> stack = new Stack<>();
stack.push(root);
do {
GraphNode cur = stack.pop();
if (cur != null && !cur.visited) {
// leaf node or all children have been visisted
if (cur.children.isEmpty() || childrenVisisted(cur)) {
System.out.println(cur);
cur.visited = true;
}
else {
// put it back
stack.push(cur);
for (GraphNode child :cur.children) {
if (!child.visited) {
stack.push(child);
}
}
}
}
}
while (!stack.isEmpty());
}
static boolean childrenVisisted(GraphNode node) {
for (GraphNode child : node.children) {
if (!child.visited) return false;
}
return true;
}
答案 0 :(得分:2)