获取给定级别的JSON树的节点数

编程入门 行业动态 更新时间:2024-10-14 06:19:58
本文介绍了获取给定级别的JSON树的节点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个带有子节点的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

更多推荐

获取给定级别的JSON树的节点数

本文发布于:2023-11-30 09:02:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649450.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!