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

树结构

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)

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理