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 {*} roots
    21. * @param {*} target
    22. * @returns
    23. */
    24. function fls (roots, target) {
    25. if(roots == null || roots.length == 0) return false;
    26. let child = [];
    27. for (let i = 0; i < roots.length; i++ ) {
    28. if(roots[i].value == target ) {
    29. return true;
    30. } else {
    31. child = child.concat(roots[i].child);
    32. }
    33. }
    34. return fls(child, target);
    35. }
    36. console.log(fls([a], 'e'));