2016-01-22 113 views
-1

我的json结构就像一个树结构。给定树结构的最大深度

+0

这必须是我读过的最通用的标题之一。 **每个**编程问题都是关于特定场景的编码逻辑。请尽量为读者提供更多帮助。 – Barmar

+0

***但它没有给出正确的结果***并没有告诉我们你的问题是什么或你想要什么帮助。究竟是什么问题?你观察到什么?结果应该是什么?要在这里获得帮助,您需要非常具体地了解问题的具体内容。请记住,我们无法读懂你的想法。我们不知道你在找什么结果。我们只能阅读你的文字和代码。 – jfriend00

回答

0

我花了一段时间才了解counter的数据结构我希望复制如何达成解决方案,但它只是松散地基于发布的代码(不适用于初学者的变量temp)。

理解以下代码的一个关键是paramListsvalue对象具有相似的结构(如果不是相同的话)。

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应该进行修改,以在新的数据对象返回值。

+0

如何在给定的算法对象中找到叶节点的no? – Jason

+0

你问这个问题吗?你有什么尝试? – traktor53