tree.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. const { Node, Link, Graph } = require("./graph");
  2. class TreeNode extends Node {
  3. constructor(id){
  4. super(id);
  5. this.depth = null;
  6. }
  7. }
  8. class Tree extends Graph {
  9. constructor(NodeType,rootNode){
  10. super(NodeType);
  11. this.root = rootNode;
  12. this.root.depth = 0;
  13. this.levels = [new Set(this.root.id)];
  14. super.addNode(this.root);
  15. }
  16. addLink(link) {
  17. console.log("You cannot add Link because its deprecated ...Use Insert");
  18. return;
  19. }
  20. addNode(node){
  21. console.log("You cannot add Node because its deprecated ...Use Insert");
  22. return;
  23. }
  24. insert(node,parentNode){
  25. if(this.nodes[node.id]){
  26. throw new Error("Node already Exists")
  27. }
  28. if(!this.nodes[parentNode.id]){
  29. throw new Error("Parent Node does not Exist....Insert First ")
  30. }
  31. let parentLevel = parentNode.depth;
  32. node.depth = parentLevel + 1;
  33. if(this.levels.length <= node.depth){
  34. this.levels[node.depth] = new Set();
  35. }
  36. this.levels[node.depth].add(node.id);
  37. let link = new Link(parentNode,node);
  38. super.addNode(node);
  39. super.addLink(link);
  40. }
  41. print() {
  42. console.log("§§§§§§§ Tree Structure §§§§§§§§§§");
  43. this.levels.forEach((level, index) => {
  44. console.log("Level ", index);
  45. level.forEach( id => console.log(` ${id} `));
  46. });
  47. console.log("§§§§§§§ Tree Structure End §§§§§§§§§§");
  48. }
  49. remove(node){
  50. this.cleanup(node)
  51. this.levels[node.depth].delete(node.id);
  52. if(this.levels[node.depth].size === 0)
  53. this.levels.length = node.depth;
  54. super.removeNode(node);
  55. }
  56. cleanup(parent){
  57. let children = this.getChildren(parent);
  58. // console.log(children);
  59. children.forEach(child => {
  60. // console.log(child);
  61. this.remove(child)
  62. });
  63. }
  64. getChildren(node){
  65. // console.log(node)
  66. return [...this.links[node.id].out].map(link => link.to);
  67. }
  68. getLevel(depth) {
  69. return this.levels[depth];
  70. }
  71. }
  72. var A = new TreeNode("A");
  73. let tree = new Tree(TreeNode,A);
  74. var B = new TreeNode('B');
  75. var C = new TreeNode('C');
  76. var D = new TreeNode('D');
  77. var E = new TreeNode('E');
  78. var F = new TreeNode("F");
  79. tree.insert(B,A)
  80. tree.insert(C,A)
  81. tree.insert(D,B)
  82. tree.insert(E,D)
  83. tree.insert(F,D)
  84. tree.print();
  85. tree.remove(D)
  86. tree.print();