Javascript 前端私房菜(四)-- 二叉树的深度遍历和广度遍历

144 阅读1分钟

1. 关于深度优先遍历

沿着树的深度遍历结点,尽可能深的搜索树的分支。如果当前的节点所在的边都被搜索过,就回溯到当前节点所在的那条边的起始节点。一直重复直到进行到发现源节点所有可达的节点为止。

因为深度优先搜索算法是先访问根节点,接着遍历左子树再遍历右子树。 为了方便,我们可以引入堆栈这个数据结构来帮我们快速解决DFS算法。 因为栈是后进先出的结构,所以我们可以先将右子树压栈,再将左子树压栈,这样左子树就位于栈顶,可以保证先遍历左子树再遍历右子树。

// 准备一个数组

const array = [  {    name: 'a',    children: [      {        name: 'b',        children: [          {            name: 'c',            children: [              {                name: 'd',              },            ],
          },
          {
            name: 'e',
            children: [
              {
                name: 'f',
              },
            ],
          },
        ],
      },
      {
        name: 'g',
        children: [
          {
            name: 'h',
            children: [
              {
                name: 'i',
              },
              {
                name: 'j',
              },
            ],
          },
        ],
      },
    ],
  },
]

// 深度优先遍历

function DepthFirstSearch(node) {
  node.forEach((item) => {
    console.log(item.name)
    const children = item.children || []
    if (children) {
      DepthFirstSearch(children)
    }
  })
}
// DepthFirstSearch(array)

2. 关于广度优先遍历

从根节点开始,沿着树的宽度遍历树的节点,直到所有节点都被遍历完为止。 因为是按照一层一层遍历的,所以我们考虑引入队列这个数据结构帮助我们实现广度优先搜索算法。

function BreadthFirstSearch(node) {
  const queue = node
  while (queue.length > 0) {
    const item = queue.shift()
    console.log(item.name)
    const children = item.children || []
    children.forEach((item) => {
      queue.push(item)
    })
  }
}
// BreadthFirstSearch(array)