# 广度优先遍历

广度优先遍历(Breadth First Search)从二叉树的根节点出发,一层一层的遍历树,每一层从左至右遍历节点

使用队列queue来存储将要遍历的节点

# 算法

const BFS = (root) => {
	if (!root) return [];
	const breadRes = [];
	const queue = [root];
	while (queue.length) {
		const node = queue.shift();
		breadRes.push(node.val);
		if (node.left) queue.push(node.left);
		if (node.right) queue.push(node.right);
	}
	return breadRes;
};
1
2
3
4
5
6
7
8
9
10
11
12