概念

深度优先遍历(Depth First Search): 尽可能深的搜索树的分支

image.png

广度优先遍历(Breath First Search):先访问离根节点最近的节点

image.png

算法思路

深度优先遍历

  • 访问根节点
  • 对根节点的children挨个进行深度优先遍历
  1. const tree = {
  2. val: 'a',
  3. children: [
  4. {
  5. val: 'b',
  6. children: [
  7. {
  8. val: 'd',
  9. children: []
  10. }, {
  11. val: 'e',
  12. children: []
  13. }
  14. ]
  15. },
  16. {
  17. val: 'c',
  18. children: [
  19. {
  20. val: 'f',
  21. children: []
  22. }, {
  23. val: 'g',
  24. children: []
  25. }
  26. ]
  27. }
  28. ]
  29. }
  30. const dfs = (root) => {
  31. console.log(root.val);
  32. root.children.forEach(dfs);
  33. }
  34. dfs(tree)

运行结果为:
a
b
d
e
c
f
g
符合深度优先遍历

广度优先遍历

  • 新建一个队列,把根节点入队
  • 把队头出队并访问
  • 把对头的children挨个入队
  • 重复第二、第三步,直到队列为空
  1. const bfs = (root) => {
  2. const queue = [root]
  3. while (queue.length) {
  4. const n = queue.shift()
  5. console.log(n.val)
  6. n.children.forEach(item => {
  7. queue.push(item)
  8. })
  9. }
  10. }
  11. bfs(tree)

运行结果为:
a
b
c
d
e
f
g
符合广度优先遍历