tree.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. class Node{
  2. constructor(value){
  3. this.value = value;
  4. this.children = [];
  5. }
  6. }
  7. class Tree {
  8. constructor(NodeType){
  9. this.root = null;
  10. this.node = NodeType;
  11. }
  12. //find node based on value
  13. search(value){
  14. if(value === this.root.value) return this.root;
  15. var stack = [], node, counter;
  16. stack.push(this.root)
  17. while(stack.length > 0){
  18. node = stack.pop()
  19. if(node.value === value){
  20. //found the value we are looking for
  21. return node;
  22. }else if(node.children && node.children.length){
  23. for(counter = 0; counter < node.children.length; counter++ ){
  24. stack.push(node.children[counter]);
  25. }
  26. }
  27. }
  28. return null;
  29. }
  30. insert(value,parent){
  31. if(this.root === null){
  32. let root =new this.node(value);
  33. this.root = root;
  34. return this.root;
  35. }else{
  36. let newNode = new this.node(value);
  37. parent.children.push(newNode);
  38. return newNode;
  39. }
  40. }
  41. remove(node){
  42. let NodeToBeRemoved = this.search(node.value);
  43. console.log("################")
  44. console.log(NodeToBeRemoved)
  45. NodeToBeRemoved = null;
  46. return this.root;
  47. }
  48. }
  49. //Initiailize tree
  50. var tree = new Tree(Node);
  51. //creating a random new node
  52. let node = new Node(5)
  53. var root = tree.insert(5)
  54. var child1 = tree.insert(1,root)
  55. var child2 = tree.insert(2,root)
  56. var child3 = tree.insert(3,root)
  57. tree.remove(child3)
  58. console.log("##############")
  59. console.log(root)