深度和广度优先遍历-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);