PHP前端开发

使用 Javascript 实现各种树算法

百变鹏仔 3天前 #JavaScript
文章标签 算法

简单的树

  1. 我们需要始终从简单的算法开始,然后一步步走向复杂的算法。
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