树-简述深度/广度优先遍历

110 阅读1分钟

深度与广度优先遍历

  • 深度优先遍历:尽可能深的搜索树的分支
  • 广度优先遍历:优先访问离根节点最近的节点

image-20210727112321086

DFS 与 BFS 对比

深度优先遍历算法口诀

  • 先访问根节点
  • 对根节点的children挨个进行深度优先遍历

深度优先遍历

 const dfs = (root) => {//接收一个根节点
     console.log(root.val);//打印根节点
     root.children.forEach(dfs);//对子节点深度优先遍历
     // root.children.forEach((child)=>{dfs(child)})
 };
 ​
 dfs(tree);
 ​
 const tree = {
     val: 'a',
     children: [
         {
             val: 'b',
             children: [
                 {
                     val: 'd',
                     children: [],
                 },
                 {
                     val: 'e',
                     children: [],
                 }
             ],
         },
         {
             val: 'c',
             children: [
                 {
                     val: 'f',
                     children: [],
                 },
                 {
                     val: 'g',
                     children: [],
                 }
             ],
         },
     ],
 };

广度优先遍历算法口诀

image-20210727112841307

  • 新建一个队列,把根节点入队
  • 把对头出队并访问
  • 把对头的children挨个入队
  • 重复第二第三步,直到队列为空

广度优先遍历

 const bfs = (root) => {
     const q = [root];//创建一个队列
     while (q.length > 0) {
         const n = q.shift();//将队头出队
         console.log(n.val);//访问对头
         n.children.forEach(child => {//挨个将对头的child入队
             q.push(child);
         });
     }
 };
 ​
 bfs(tree);