/**
* 从某个节点开始宽度优先遍历,也叫广度优先遍历
*
* @param node
*/
public static void bfs(Node node) {
if (node == null) {
return;
}
Deque<Node> queue = new LinkedList<>();
Set<Node> set = new HashSet<>();
queue.add(node);
set.add(node);
while (!queue.isEmpty()) {
Node poll = queue.poll();
System.out.println(poll.value);
for (Node next : poll.nexts) {
if (!set.contains(next)) {
queue.add(next);
set.add(next);
}
}
}
}
/**
* 深度优先遍历,
*
* @param node
*/
public static void dfs(Node node) {
if (node == null) {
return;
}
Deque<Node> stack = new LinkedList<>();
Set<Node> set = new HashSet<>();
stack.add(node);
set.add(node);
System.out.println(node.value);
while (!stack.isEmpty()) {
Node pop = stack.pop();
for (Node next : pop.nexts) {
if (!set.contains(next)) {
stack.push(pop);
stack.push(next);
set.add(next);
System.out.println(next.value);
break;
}
}
}
}