二叉树的层遍历。
广度优先 和 二叉树 并不是绑定关系。也可以这么说,广度优先和深度优先都算不上算法,只能说是核心基础代码能力的考察。
模版:(经典的写法)
function test(nums) {const queue = [first]; // 初始条件!!while (queue.length > 0) {let size = queue.length; // 固定这一层要遍历的范围for (let i = 0; i < size; i++) {let curWord = queue.shift(); // 弹出处理本层// 为一层添加东西queue.push(curWord.nextSon());queue.push(curWord.nextSon());}// queue 此时仅包含下一层所有东西for (let item of queue) {// ...}}}
127. Word Ladder
在搜索接龙单词时,按照流程,我们要一层一层搜索:
比如 big 的下一个单词可能是 bag bug …. 再由bag 和 bug 来扩展就可以。
var ladderLength = function(beginWord, endWord, wordList) {if (wordList.length === 0 || !wordList.includes(endWord)) {return 0;}const wordDict = new Set(wordList); // set 查找速度比 array 快的多const queue = [beginWord];let step = 1;while (queue.length > 0) {let size = queue.length;for (let i = 0; i < size; i++) {let curWord = queue.shift();const result = didMatch(curWord, endWord);if (result) {return step + 1;}}step++;}function didMatch(curWord, targetWord) { // curWord 和 targetWord 长度相同for (let i = 0; i < curWord.length; i++) { // 每个字符都要替换比较for (let c = 97; c < 123; c++) {let changedChar = String.fromCharCode(c);let changedWord = curWord.slice(0, i) + changedChar + curWord.slice(i + 1);if (changedWord === targetWord) { // 找到了最终的return true;}if (wordDict.has(changedWord)) { // 找到了半成品queue.push(changedWord);wordDict.delete(changedWord); // 匹配过的就删了}}}return false;}return 0;};
