class simpletree { constructor(value) { this.value = value; this.children = []; } insertchild(value) { const newchild = new simpletree(value); const lastelement = this.findlastchild(this); lastelement.children.push(newchild); return newchild; } findlastchild(root) { if (root.children.length == 0) { return root; } return this.findlastchild(root.children[0]); } traversal(root) { console.log(root.value + ' --> '); root.children.foreach(child => { this.traversal(child); }) } } const simpletree = new simpletree('a'); simpletree.insertchild('b'); simpletree.insertchild('c'); simpletree.insertchild('d'); simpletree.insertchild('e'); simpletree.insertchild('f'); console.log(simpletree) simpletree.traversal(simpletree) /* { "value": "a", "children": [ { "value": "b", "children": [ { "value": "c", "children": [ { "value": "d", "children": [ { "value": "e", "children": [ { "value": "f", "children": [] } ] } ] } ] } ] } ] } */
class BinaryTree { constructor(value) { this.value = value; this.left = null; this.right = null; } insertNode(value) { const newNode = new BinaryTree(value); const {node: lastNode, side} = this.findAppropriatePlace(this, value); lastNode[side] = newNode; return newNode; } removeFromNode(value) { this.findAppropriateNodAndrRemove(this, value); } findAppropriateNodAndrRemove(root, value) { const side = root.value