Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. class Node {
  2. constructor(data) {
  3. this.data = data;
  4. this.children = [];
  5. }
  6.  
  7. add(data) {
  8. this.children.push(new Node(data));
  9. }
  10.  
  11. remove(data) {
  12. this.children = this.children.filter(node => node.data !== data);
  13. }
  14. }
  15.  
  16. class Tree {
  17. constructor() {
  18. this.root = null;
  19. }
  20.  
  21. traverseBF(fn) {
  22. const arr = [this.root];
  23. while (arr.length) {
  24. const node = arr.shift();
  25.  
  26. arr.push(...node.children);
  27. fn(node);
  28. }
  29. }
  30.  
  31. traverseDF(fn) {
  32. const arr = [this.root];
  33. while (arr.length) {
  34. const node = arr.shift();
  35.  
  36. arr.unshift(...node.children);
  37. fn(node);
  38. }
  39. }
  40. }
  41.  
  42. // Implementation
  43. // const node = new Node(1);
  44. // const tree = new Tree();
  45. // tree.root = node;
  46.  
  47. module.exports = { Tree, Node };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement