深度和广度优先遍历-JS实现
1 const tree = { 2 val: 'a', 3 children: [ 4 { 5 val: 'b', 6 children: [ 7 { 8 val: 'd', 9 children:[], 10 }, 11 { 12 val: 'e', 13 children:[], 14 } 15 ], 16 }, 17 { 18 val: 'c', 19 children: [ 20 { 21 val: 'f', 22 children:[], 23 }, 24 { 25 val: 'g', 26 children:[], 27 } 28 ] 29 } 30 ] 31 } 32 // 深度优先遍历 33 const dfs = (root) => { 34 console.log(root.val); 35 root.children.forEach(dfs); 36 } 37 dfs(tree); 38 39 // 广度优先遍历 40 const bfs = (root) => { 41 const q = [root]; 42 while (q.length > 0) { 43 const n = q.shift(); 44 console.log(n.val); 45 n.children.forEach(child => { 46 q.push(child); 47 }); 48 } 49 }; 50 51 bfs(tree);
本文作者:oaoa
本文链接:https://www.cnblogs.com/oaoa/p/14841836.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步