简单的树
- 我们需要始终从简单的算法开始,然后一步步走向复杂的算法。
- 简单的树
- 二叉树
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
以上就是使用 Javascript 实现各种树算法的详细内容,更多请关注php中文网其它相关文章!
版权声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系 yyfuon@163.com