深度优先遍历(DFS)

对于树的每个节点,采用先序遍历(左 — 根 — 右)。
image.png

  1. // 对于树的每个节点,采取从左到右的形式
  2. const { tree } = require('./tree_data')
  3. const dfs = root => {
  4. if(!root) return;
  5. console.log(root.val);
  6. root.children.forEach(child => {
  7. dfs(child)
  8. })
  9. }
  10. dfs(tree)

广度优先遍历

沿着树的广度遍历节点
image.png

  1. // 从根节点开始入队,每出队一个节点,将其所有子节点从左到右入队,直至队空
  2. const { tree } = require('./tree_data')
  3. const bfs = root => {
  4. if(!root) return;
  5. const queue = [root];
  6. while(queue.length) {
  7. const top = queue.shift();
  8. console.log(top.val);
  9. top.children.forEach(child => {
  10. queue.push(child)
  11. })
  12. }
  13. }
  14. bfs(tree)