何为深度搜索

image.png
如上图 假如进入深度搜索
搜索顺序为
A — C — F — G —B — 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 {*} root 开始值//根节点
  24. * @param {*} target 目标值
  25. * @returns
  26. */
  27. function f1(root , target){
  28. if(root == null || target == null ) return false;
  29. if(root.value == target){
  30. return true;
  31. }
  32. var left = f1(root.left,target);
  33. var right = f1(root.right,target);
  34. return left || right;
  35. }
  36. console.log(f1(a,"o"))