Sto cercando di imparare bene le strutture di dati e implementato il seguente codice per una profondità prima attraversamento/applicazione di un callback su un albero normale:breadth-first attraversamento di un albero in javascript
Tree.prototype.traverse = function (callback) {
callback(this.value);
if (!this.children) {
return;
}
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
child.traverse(callback);
}
};
Come potrebbe Io cambio questo per renderlo prima di tutto invece? Questo è ciò che la classe Tree assomiglia:
var Tree = function (value) {
var newTree = {};
newTree.value = value;
newTree.children = [];
extend(newTree, treeMethods);
return newTree;
};
è possibile sostituire il per con 'pila = stack.concat (n.children) ' –
@AndrasSzell che cambierebbe la complessità dell'algoritmo da O (| V | + | E |) a O (| V |^2 + | E |), poiché concat() assegna un nuovo array. –
L'array in JS è fondamentalmente una tabella hash, quindi non c'è differenza di complessità tra concat e push. –