何为广度优先搜搜

image.png
如上图 假如进行广度优先搜索的顺序为
A — C — B —F — G — D — E
广度优先搜索,同一行的搜索完后再去搜索下一行
代码实现广度优先搜索

  1. class Node {
  2. constructor(value) {
  3. this.value = value;
  4. this.left = null;
  5. this.right = null;
  6. }
  7. }
  8. let a = new Node("a")
  9. let b = new Node("b")
  10. let c = new Node("c")
  11. let d = new Node("d")
  12. let e = new Node("e")
  13. let f = new Node("f")
  14. let g = new Node("g")
  15. a.left = c;
  16. c.left = f;
  17. b.left = d;
  18. a.right = b;
  19. b.right = e;
  20. c.right = g;
  21. /**
  22. * 广度优先搜搜
  23. * @param {*} rootList 查询列表
  24. * @param {*} target 目标值
  25. * @returns
  26. */
  27. function f1(rootList , target){
  28. if(rootList == null || rootList.length == 0) return false;
  29. var childList = []
  30. for (let i = 0; i < rootList.length; i++) {
  31. if(rootList[i].value!= null) return false;
  32. if(rootList[i] != null && rootList[i].value == target){
  33. return true;
  34. }else{
  35. childList.push(rootList[i].left)
  36. childList.push(rootList[i].right)
  37. }
  38. }
  39. return f1(childList , target)
  40. }
  41. console.log(f1([a],"o"))