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

前端 未结 4 1812
悲&欢浪女
悲&欢浪女 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:24

    If you want to do some calculation at every node in the tree then you could add a traverse function to your tree nodes, something like:

    Tree.prototype.traverse = function( operation ){
        // call the operation function and pass in the current node
        operation( this )
    
        // call traverse on every child of this node
        for( var i=0; i

    Alternatively if you're doing something more specific such as manipulating the tree or finding a particular node then you may want to look at the Visitor Design Pattern.

提交回复
热议问题