2016-07-21 97 views
1

我有一個D3樹基於以下的所有兒童...D3樹算

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

我怎麼會得到所有的孩子的計數?我曾經嘗試這樣做不過它計算樹中的所有行...

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

因此在本例中,應該都算,孩子們將在橘子樹有色行(像那些在集羣中的孩子,圖表等)。

感謝您的任何見解!

回答

3

我實際上有一個類似的問題,我必須從特定節點下面的樹中獲取所有描述。在我和你的情況下,答案是遞歸下降樹,並在下降的過程中做一些事情。應該看起來像這樣。

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++; 
      } 
     } 
    } 

注意:如果要計算所有節點下的節點,而不是僅僅在樹底的那些的,只需添加一個計數++裏面的,如果還有其他人。

+0

什麼是「遞歸」?你的意思是'count_leaves'? –

+1

是的,對不起。當我第一次寫它時,我稱它爲遞歸。我改變了這個帖子 –