dfs js实现
DFS(深度优先搜索)的 JavaScript 实现
深度优先搜索(DFS)是一种用于遍历或搜索树或图的算法。以下是几种常见的实现方式:

递归实现(适用于树或图)
function dfs(node, visited = new Set()) {
if (!node || visited.has(node)) return;
visited.add(node);
console.log(node.value); // 处理当前节点
// 遍历邻居节点(图)或子节点(树)
for (const neighbor of node.neighbors) {
dfs(neighbor, visited);
}
}
迭代实现(使用栈)
function dfs(startNode) {
const stack = [startNode];
const visited = new Set();
while (stack.length > 0) {
const node = stack.pop();
if (!visited.has(node)) {
visited.add(node);
console.log(node.value); // 处理当前节点
// 将邻居节点逆序压入栈中(保证顺序)
for (let i = node.neighbors.length - 1; i >= 0; i--) {
stack.push(node.neighbors[i]);
}
}
}
}
针对二叉树的DFS实现
// 前序遍历
function preorder(root) {
if (!root) return;
console.log(root.val);
preorder(root.left);
preorder(root.right);
}
// 中序遍历
function inorder(root) {
if (!root) return;
inorder(root.left);
console.log(root.val);
inorder(root.right);
}
// 后序遍历
function postorder(root) {
if (!root) return;
postorder(root.left);
postorder(root.right);
console.log(root.val);
}
图的DFS实现(处理环)
function graphDFS(startNode) {
const visited = new Set();
const stack = [startNode];
while (stack.length) {
const node = stack.pop();
if (visited.has(node)) continue;
visited.add(node);
console.log(node.value);
for (const neighbor of node.neighbors) {
if (!visited.has(neighbor)) {
stack.push(neighbor);
}
}
}
}
注意事项
- 对于图结构,必须使用
visited集合来避免循环和重复访问 - 递归实现可能导致调用栈溢出,对于深度大的结构建议使用迭代实现
- 时间复杂度为O(V+E),其中V是顶点数,E是边数
- 空间复杂度为O(V),最坏情况下需要存储所有节点
这些实现可以根据具体需求进行调整,例如添加回调函数代替console.log,或返回遍历结果等。






