关于javascript:深度和广度优先遍历

2次阅读

共计 650 个字符,预计需要花费 2 分钟才能阅读完成。

树结构

const tree = {
    val: 'a',
    children: [
        {
            val: 'b',
            children: [
                {
                    val: 'd',
                    children: null
                },
                {
                    val: 'e',
                    children: null
                }
            ]
        },
        {
            val: 'c',
            children: [
                {
                    val: 'f',
                    children: null
                },
                {
                    val: 'g',
                    children: null
                }
            ]
        }
    ]
}


1、深度优先遍历(DFS)

  • 拜访根节点
  • 对根节点的 children 挨个进行 DFS
const dfs = (root) => {if (!root.val) return
    console.log(root.val) // 拜访根节点
    if (root.children) root.children.forEach(dfs) // 对根节点的 children 挨个进行 dfs
}

dfs(tree)

2、广度优先遍历(BFS)

  • 新建一个队列,将根节点入队
  • 队头出队并拜访
  • 队头的 children 挨个入队
  • 反复二、三步直至队列为空
const bfs = (root) => {const queue = [root] // 1、新建一个队列,将根节点入队
    while(queue.length) { // 4、队列为空,跳出循环
        const head = queue.shift() // 2、队头出队
        console.log(head.val) // 2、访问队头
        if (head.children) { // 3、队头的 children 顺次入队
            head.children.forEach(child => queue.push(child))
        }
    }
}

bfs(tree)

正文完
 0