卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章73023本站已运行431

使用 Javascript 实现各种树算法

使用 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 




          

            
        
卓越飞翔博客
上一篇: 如何利用审计日志功能来增强Golang框架的安全性?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏