image.png
    这是树的深度优先搜索并不是二叉树的深度优先搜索
    实现源码

    1. class Node {
    2. constructor(value) {
    3. this.value = value;
    4. this.child = [];
    5. }
    6. }
    7. const A = new Node('A')
    8. const B = new Node('B')
    9. const C = new Node('C')
    10. const D = new Node('D')
    11. const E = new Node('E')
    12. const F = new Node('F')
    13. A.child.push(C)
    14. A.child.push(F)
    15. A.child.push(B)
    16. B.child.push(D)
    17. B.child.push(E)
    18. /**
    19. * 树的深度优先搜索
    20. * @param {*} root 节点
    21. */
    22. function deepNode(root) {
    23. if (root == null) return
    24. console.log(root.value)
    25. for (let i = 0; i < root.child.length; i++) {
    26. let newRoot = root.child[i]
    27. deepNode(newRoot)
    28. }
    29. }
    30. deepNode(A)

    打印结果
    image.png
    最终的代码

    1. class node {
    2. constructor(value) {
    3. this.value = value;
    4. this.child = [];
    5. }
    6. }
    7. const a = new node('a');
    8. const c = new node('c');
    9. const f = new node('f');
    10. const b = new node('b');
    11. const d = new node('d');
    12. const e = new node('e');
    13. a.child.push(c);
    14. a.child.push(f);
    15. a.child.push(b);
    16. b.child.push(d);
    17. b.child.push(e);
    18. /**
    19. * 树的深度优先搜索
    20. * @param {*} root
    21. * @param {*} target
    22. * @returns
    23. */
    24. function deepSearch(root,target) {
    25. if(root == null) return false;
    26. if(root.value == target) return true;
    27. let result = false;
    28. for(let i = 0; i < root.child.length; i++) {
    29. result = deepSearch(root.child[i], target);
    30. }
    31. return result
    32. }
    33. console.log(deepSearch(a, 'e'))