深度优先遍历(DFS)
对于树的每个节点,采用先序遍历(左 — 根 — 右)。
// 对于树的每个节点,采取从左到右的形式const { tree } = require('./tree_data')const dfs = root => {if(!root) return;console.log(root.val);root.children.forEach(child => {dfs(child)})}dfs(tree)
广度优先遍历
沿着树的广度遍历节点
// 从根节点开始入队,每出队一个节点,将其所有子节点从左到右入队,直至队空const { tree } = require('./tree_data')const bfs = root => {if(!root) return;const queue = [root];while(queue.length) {const top = queue.shift();console.log(top.val);top.children.forEach(child => {queue.push(child)})}}bfs(tree)
