树遍历优化

时间:2017-01-14 06:09:21

标签: javascript data-structures tree binary-search-tree tree-traversal

我在JavaScript中使用嵌套对象(例如

)有一个简单的树数据结构
class Node {
    name: "",
    children: [
       ...Node
    ]
}

rootNode=[Node, Node, Node...]

现在,

我遍历树并找到匹配谓词的所有节点,如

 let result =[];
 let allNodes =[];
 if isArray(rootNode) {
     rootNode.each(x=>{
         allNodes.push(x)
     });
 } else {
     allNodes.push(rootNode);
 }

while (allNodes.length) {
    let currentNode = allNodes.shift();
    if (predicate(currentNode) {
          result.push(currentNode);
    }
    if (currentNode.children.length) {

         allNodes.push(addAllChild(currentNode.children))
     }

 }

上面有什么有效的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以递归方式执行此操作,因为您不需要按特定顺序执行此操作。在这里,您没有在allNodes中存储所有节点引用的开销,并且由于尾调用优化,这段代码可能比迭代代码运行得更快:

async function _validateCategories() {
  this.apiService.fetchCategories(!this.cacheData).subscribe(
    response => {
        this._jsnValService.valCategories(response).then((error, valid)=> {
        if(error) {
            alert("Categories failed the schema validation. Please contact support if this happens again.");
        }
        this.customerMap.categories = this.formatCategories(response["categories"]);
        })
    },
    error => {
        this.notification.title = "Oops, there's a problem.";
        this.notification.content = "Seems there's an issue getting the provider categories.";
        this.notification.show("provider_categories_api");
    }
  );
}