Home >Web Front-end >JS Tutorial >Approaching Various Tree Algorithm using Javascript
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
The above is the detailed content of Approaching Various Tree Algorithm using Javascript. For more information, please follow other related articles on the PHP Chinese website!