tree.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. class Link {
  2. constructor(to, from) {
  3. this.from = from;
  4. this.to = to;
  5. }
  6. }
  7. class Node {
  8. constructor(id){
  9. this.id = id;
  10. }
  11. }
  12. class Tree {
  13. constructor(NodeType){
  14. this.root = new NodeType(-1);
  15. this.links = {
  16. [this.root.id]: this._emptyLink()
  17. };
  18. }
  19. _emptyLink() {
  20. return {
  21. out: new Set(),
  22. in: null
  23. };
  24. }
  25. updateLinkOut(node, link) {
  26. this.links[node.id].out.add(link);
  27. }
  28. updateLinkIn(node, link) {
  29. this.links[node.id].in = link;
  30. }
  31. insert(node, parentNode = this.root) {
  32. this.links[node.id] = this._emptyLink();
  33. let newLink = new Link(node,parentNode);
  34. this.updateLinkIn(node, newLink);
  35. this.updateLinkOut(parentNode, newLink);
  36. }
  37. traverseTree(current) {
  38. if(!current) current = this.root;
  39. console.log(current.id);
  40. let set = this.links[current.id].out;
  41. return set.forEach((link, index) => {
  42. let next = link.to;// WOW
  43. return next && this.traverseTree(next);
  44. });
  45. }
  46. bfs(current = this.root) {
  47. if(!current) current = this.root;
  48. var stack = [current] , node;
  49. while(stack.length > 0) {
  50. node = stack.shift();
  51. let set = this.links[node.id].out;
  52. set.forEach((item) => stack.push(item.to));
  53. // Do something
  54. console.log(node.id)
  55. }
  56. }
  57. removeLink(link) {
  58. let parentOut = this.links[link.from.id].out;
  59. parentOut.delete(link);
  60. this.links[link.to.id].in = null;
  61. }
  62. removeNode(node){
  63. let link = this.links[node.id].in;
  64. this.removeLink(link);
  65. return node;
  66. }
  67. updateNode(node, newNode) {
  68. //update Links
  69. }
  70. updateLink(link, newLink) {
  71. // update Link
  72. }
  73. }
  74. var tree = new Tree(Node);
  75. var child1 = new Node(1);
  76. var child2 = new Node(2);
  77. tree.insert(child1);
  78. tree.insert(child2);
  79. tree.insert(new Node('L2-1-1'), child1);
  80. tree.insert(new Node('L2-1-2'), child1);
  81. tree.insert(new Node('L2-2-1'), child2);
  82. tree.traverseTree();
  83. console.log("----- BFS ---- ");
  84. tree.bfs();
  85. tree.removeNode(child1);
  86. console.log("----- BFS ---- Child1");
  87. tree.bfs(child1);