LeetCode练题六:dfs与bfs

(1)定义树这种数据结构

javascript 复制代码
// 先定义数据结构
const root = {
    val: 1
    children: {
        {
            val:2
            children: {
                {
                    val:4
                },
                {
                    val:5
                }
            }   
        },
        {
            val:3
            children: {
                {
                    val:6
                },
                {
                    val:7
                }
            }
        }
    }
}

(2)dfs深度优先遍历:就是一直让

javascript 复制代码
const dfs = (root) => {
    console.log(root.val)
    root.children.forEach(dfs)
}

(3)bfs广度优先遍历:就是不断出队,然后把自己的孩子放进去

javascript 复制代码
const bfs = (root) => {
    const q = [root]
    while(q.length > 0) {
        const n = q.shift()
        console.log(n)
        n.children.forEach(n => {
            q.push(n)
        })
    }
}
相关推荐
文丑颜不良啊4 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z4 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
文丑颜不良啊6 小时前
LeetCode2161~2180题目解析
java·leetcode
文丑颜不良啊7 小时前
LeetCode2141~2160题目解析
java·leetcode
Dream it possible!1 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊1 天前
算法之双指针系列(一)
算法·leetcode
Pniubi1 天前
力扣560.和为k的子数组
算法·leetcode·职场和发展
Pniubi1 天前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
文丑颜不良啊1 天前
LeetCode2081~2100题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2061~2080题目解析
java·leetcode