【问题标题】:d3 tree count all childrend3 树计算所有孩子
【发布时间】:2016-11-25 14:50:15
【问题描述】:

我有一个基于以下内容的 d3 树...

http://bl.ocks.org/mbostock/1093025

如何计算所有孩子的数量?我已经尝试过了,但是它计算了树中的所有行...

$(".tree_badge").text(tree.links(nodes).length);

因此,在示例中,它应该计算所有子节点,其中子节点将是树中的橙色行(例如集群、图表等中的子节点)。

感谢您的任何见解!

【问题讨论】:

    标签: javascript arrays d3.js tree


    【解决方案1】:

    我实际上有一个类似的问题,我必须从特定节点下方的树中获取所有描述。在我和你的情况下,答案是递归地下降树并在下降的过程中做一些事情。应该看起来像这样。

    var count;
    
    function count_leaves(node){
        if(node.children){
            //go through all its children
            for(var i = 0; i<node.children.length; i++){
                //if the current child in the for loop has children of its own
                //call recurse again on it to decend the whole tree
                if (node.children[i].children){
                    count_leaves(node.children[i]);
                }
                //if not then it is a leaf so we count it
                else{
                    count++;
                }
            }
        }
    

    注意:如果您想计算节点下方的所有节点,而不仅仅是树末端的节点,只需在 if 和 else 中添加 count++。

    【讨论】:

    • 什么是recurse?你的意思是count_leaves
    • 是的,对不起。当我第一次写它时,我称之为递归。我为这篇文章更改了它
    【解决方案2】:

    只需使用leaves 方法

    由于我是从谷歌来到这里寻找how to optimally count each children's descendants,所以解决方案是

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2017-06-10
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多