[英]How to avoid walking the tree twice
我有以下方法來初始化一棵樹:
function _initTree(treeObj, options){
treeObj = treeObj || [];
if(!zpJSUtils.isArray(treeObj)) throw new Error("Input tree must be an array");
this.tree = treeObj;
this.rootNode = treeObj[0];
_buildNodes.call(this, treeObj);
}
init
方法遍歷樹以將所有對象初始化為節點:
function _buildNodes(treeObj){
traverseTree.call(treeObj, function(nodeObj){
node = new Node(nodeObj);
return true;
}, this);
}
traverseTree 方法(從一個開關中選擇):
function _walkPreOrder(tree, callback, ctx){
tree.forEach(function(node, idx){
var continueWalk = callback.call(ctx, node);
if(continueWalk){
if(node.hasChildren()){
_walkPreOrder.call(this, node);
};
};
}, this);
}
問題是這個。
我想在 init 上計算樹的高度,它是根節點和葉子之間最長向下路徑上的邊數。
所以似乎為了計算高度,我必須再次遍歷樹(以找到最深嵌套元素的級別)。
json的格式是這樣的:
var json = [{ text: "root", children: [
{id: "id_1", text: "node_1", children:[
{id: "id_c1", text: "node_c1"},
{id: "id_c2", text: "node_c2", children: [
{id: "id_c2_c1", text: "node_c2_c1"},
{id: "id_c2_c2", text: "node_c2_c2"},
{id: "id_c2_c3", text: "node_c2_c3"}]},
{id: "id_c3", text: "node_c3"}]},
{id: "id_2", text: "node_2"}]}];
問題是_walkPreOrder
可以接受多個回調(例如數組),但這會導致可疑的 api(因為傳入多個函數使得當條件為真/假時有可能繼續遍歷樹)。
什么是解決這個問題的好方法,即避免多次迭代?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.