我的json結構就像一個樹結構。給定樹結構的最大深度
-1
A
回答
0
我花了一段時間才瞭解counter
的數據結構我希望複製如何達成解決方案,但它只是鬆散地基於發佈的代碼(不適用於初學者的變量temp
)。
理解以下代碼的一個關鍵是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
應該進行修改,以在新的數據對象返回值。
相關問題
- 1. 樹結構的最大深度
- 2. 最大樹深度在Haskell
- 3. 深度在樹形結構中的BigQuery
- 4. B型樹的最大深度
- 5. 查找二叉樹的最大深度
- 6. 尋找樹的最大深度
- 7. 查找樹的最大深度
- 8. 樹的最大深度,使用隊列
- 9. 角UI樹限制最大深度
- 10. 給予2D結構的3D深度
- 11. 將文件保存到樹給定的樹未知樹深度
- 12. 什麼是C#中固定深度樹狀數據的最佳數據結構?
- 13. 樹結構:驗證樹的深度級別
- 14. 給定深度處的子樹中的節點數,給定主樹中所有節點的深度
- 15. 大小爲1的二叉樹的最大深度
- 16. 確定樹的深度
- 17. Sqlite的錯誤:表達式樹太大(最大深度1000)
- 18. 給定結構的大小
- 19. AutoMapper:最大圖的深度
- 20. 表達式樹太大(最大深度1000)sqlite windows
- 21. UINavigationController中的UITableViewController來表示未知深度的樹結構
- 22. 的MongoDB - 骨料深樹結構
- 23. 二叉樹的最小深度
- 24. 找到最小化樹深度的根
- 25. 計算樹的深度Java數據結構
- 26. 如何獲得html樹的最大深度?
- 27. 尋找二元搜索樹(BST)的最大深度
- 28. FETCH JOIN最大深度?
- 29. Python:最大遞歸深度
- 30. 瓶最大遞歸深度
這必須是我讀過的最通用的標題之一。 **每個**編程問題都是關於特定場景的編碼邏輯。請儘量爲讀者提供更多幫助。 – Barmar
***但它沒有給出正確的結果***並沒有告訴我們你的問題是什麼或你想要什麼幫助。究竟是什麼問題?你觀察到什麼?結果應該是什麼?要在這裏獲得幫助,您需要非常具體地瞭解問題的具體內容。請記住,我們無法讀懂你的想法。我們不知道你在找什麼結果。我們只能閱讀你的文字和代碼。 – jfriend00