Javascript 给定树结构的最大深度
我的json结构就像一个树状结构。花了一段时间才理解Javascript 给定树结构的最大深度,javascript,html,arrays,json,logic,Javascript,Html,Arrays,Json,Logic,我的json结构就像一个树状结构。花了一段时间才理解计数器的数据结构我希望复制如何获得解决方案,但它只是松散地基于发布的代码(对于初学者来说,没有temp变量) function findCounterDepth( counter) { var maxDepth = 0; counter.algoList.forEach( function( algo) { findParamListDepth(algo.paramList, 0); }); funct
计数器的数据结构
我希望复制如何获得解决方案,但它只是松散地基于发布的代码(对于初学者来说,没有temp
变量)
function findCounterDepth( counter)
{ var maxDepth = 0;
counter.algoList.forEach( function( algo)
{ findParamListDepth(algo.paramList, 0);
});
function findParamListDepth(paramList, depth)
{ ++depth;
paramList.forEach( function (paramObj)
{ var child = paramObj.svalue || paramObj.paramList;
if( child)
{ findParamListDepth(child, depth);
return;
}
});
maxDepth = Math.max(maxDepth, depth);
}
return maxDepth;
}
findCounterDepth(counter);
//= 4
理解以下代码的关键是paramList
和svalue
对象的结构相似(如果不是相同的话)
function findCounterDepth( counter)
{ var maxDepth = 0;
counter.algoList.forEach( function( algo)
{ findParamListDepth(algo.paramList, 0);
});
function findParamListDepth(paramList, depth)
{ ++depth;
paramList.forEach( function (paramObj)
{ var child = paramObj.svalue || paramObj.paramList;
if( child)
{ findParamListDepth(child, depth);
return;
}
});
maxDepth = Math.max(maxDepth, depth);
}
return maxDepth;
}
findCounterDepth(counter);
//= 4
编辑 为每个算法对象添加叶节点数并不复杂。此处,计数被添加为算法对象的
dataLeafCount
属性:
function findCounterDepth( counter)
{ var maxDepth = 0;
var leafCount = 0; // add a leaf counter
counter.algoList.forEach( function( algo)
{ leafCount = 0; // zero leaf count per algorithm object
findParamListDepth(algo.paramList, 0);
algo.dataLeafCount = leafCount; // store as "dataLeafCount" property
});
function findParamListDepth(paramList, depth)
{ ++depth;
paramList.forEach( function (paramObj)
{ var child = paramObj.svalue || paramObj.paramList;
if( child)
{ findParamListDepth(child, depth);
return;
}
++leafCount; // it doesn't have children, increment leaf count;
});
maxDepth = Math.max(maxDepth, depth);
}
return maxDepth;
}
findCounterDepth(counter); //= 4
counter.algoList[0].dataLeafCount; //= 4
counter.algoList[1].dataLeafCount; //= 4
请注意,如果需要保持输入对象的不变性,则应修改
findCounterDepth
以返回新数据对象中的值。这必须是我读过的最通用的标题之一。每个编程问题都与特定场景的编码逻辑有关。请尽量为读者提供更多的帮助。但它并没有给出正确的结果,也没有告诉我们你的问题是什么,或者你需要什么帮助。到底是什么问题?你观察到了什么?结果应该是什么?要在这里获得帮助,您需要非常具体地说明问题的具体内容。记住,我们无法读懂你的心思。我们不知道你想要什么结果。我们只能阅读您的文字和代码。如何在给定的算法对象中找到叶节点的编号?您在问题中问过吗?你试过什么?