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)
        })
    }
}
相关推荐
Nil2085 小时前
leetcode 49字母异位分组
算法·leetcode·哈希算法
Nil20820 小时前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_6745719720 小时前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂21 小时前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin7701 天前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao1 天前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1231 天前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi1 天前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2082 天前
leetcode 64最小路径和
算法·leetcode·职场和发展