获取给定级别的JSON树的节点数 [英] Get number of nodes at given level of JSON tree

查看:112
本文介绍了获取给定级别的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树的节点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆