我有一个带有子节点的JSON树结构,并且我想知道在结构的给定级别上存在多少个节点.我目前有这种递归结构:
I have a JSON tree structure with nodes that have children, and I would like to know how many nodes exist at a given level of the structure. I currently have this recursive structure:
var getNumNodesAtLevel = function (node, curr, desired) { if (curr === (desired - 1)) { return node.children.length; } else { var children = node.children; children.forEach(function (child) { return getNumNodesAtLevel(child, curr + 1, desired); }); } };这行不通-任何帮助将不胜感激!
This doesn't work - any help would be appreciated!
推荐答案您已经关闭.您只需要将孩子的长度存储在某个地方即可.
You were close. You just had to store the children lengths somewhere.
一旦达到的水平比所需的水平小,该函数将返回子级的长度.
Once one level fewer than the desired is reached, the function returns the length of children.
树中所有较高的节点只会将从子节点收集的值加到零,并将其传递回直到到达根节点为止.
All the nodes higher in the tree will just add the values collected from children to zero and pass that back until root node is reached.
var getNumNodesAtLevel = function(node, curr, desired) { if (curr === (desired - 1)) return node.children.length; var count = 0; node.children.forEach(function(child) { count += getNumNodesAtLevel(child, curr + 1, desired); }); return count; };这种方法的问题是,当所需级别大于树的深度或为零(根级别,应返回1)时,将返回0.
The problem with this approach is that 0 will be returned when the desired level is larger than the depth of the tree or when it is zero (root level, should return 1).
要解决此问题,您可以关闭并检查有问题的值.
To remedy that, you could make a closure and check for problematic values.
也不必每次都手动发送起始级别.
It is also not necessary to send the starting level manually each time.
var test = { children : [ { children : [ { children : [ ] } ] }, { children : [ ] }, { children : [ { children : [ ] } ] } ] }; var getNumNodesAtLevel = (function() { var getNumNodesAtLevel = function(node, curr, desired) { if (curr === (desired - 1)) return node.children.length; var count = 0; node.children.forEach(function(child) { count += getNumNodesAtLevel(child, curr + 1, desired); }); return count; }; return function(root, desired) { if (desired === 0) return 1; var count = getNumNodesAtLevel(root, 0, desired); if (count === 0) return null; // you could throw an error here return count; }; }()); console.log(getNumNodesAtLevel(test, 0)); // 1 console.log(getNumNodesAtLevel(test, 1)); // 3 console.log(getNumNodesAtLevel(test, 2)); // 2 console.log(getNumNodesAtLevel(test, 3)); // null console.log(getNumNodesAtLevel(test, 4)); // null