I need to create a custom tree data-structure using JavaScript

前端 未结 4 1802
悲&欢浪女
悲&欢浪女 2021-02-10 18:14

I looked up this basic format for a tree structure in javascript:

function Tree(parent, child, data) {
    this.parent = parent;
    this.children = child || [];         


        
4条回答
  •  暖寄归人
    2021-02-10 18:48

    var Tree = function () {
        Tree.obj = {};
        return Tree;
    };
    
    // Parent Will be object
    Tree.AddChild = function (parent, child) {
    
        if (parent === null) {
            if (Tree.obj.hasOwnProperty(child)) {
                return Tree.obj[child];
            } else {
                Tree.obj[child] = {};
                return Tree.obj[child];
            }
        } else {
            parent[child] = {};
            return parent[child];
        }
    };
    
    
    // Uses
    
    // Inserting - 
    var t = Tree();
    var twoDoor = t.AddChild(null, "2 Door");
    var fdoor = t.AddChild(null, "4 Door");
    t.AddChild(fdoor, "manual");
    t.AddChild(twoDoor, "automatic");
    var man = t.AddChild(twoDoor, "manual");
    t.AddChild(man, "Extended Cab");
    console.log(t.obj);

提交回复
热议问题