数据结构|图论DFS&&BFS_JavaScript

李雨喵

关注

阅读 74

2022-02-19

代码实现

BFS (广度优先搜索)

function BFS(node) {
	let nodeList = [];
	if (node) {
		let temp = [];
		temp.unshift(node);
		while (temp.length) {
			let item = temp.shift();
			nodeList.push(item);
			let children = item.chidren;
			for (let i = 0; i < children.length; i++) {
				temp.push(children[i])
			}
		}
	}
	return nodeList
}

DFS (深度优先搜索)

let nodeList = [];
function DFS(node,nodeList) {
	if (node) {
		nodeList.push(node);
		let children = node.children;
		for (let i = 0; i < children.length; i++) {
			DFS(children[i],nodeList)
		}
	}
	return nodeList
}

精彩评论(0)

0 0 举报