2015-06-15 47 views
0

所以我的編碼練習被賦予節點計數其子女的參考。 我已經決定使用遞歸,我想知道這是一種優雅的方式來做到這一點:Recusively計數二叉樹中的兒童節點

假設有代表樹中的每個節點類節點:

public Node { 
    int data: 
    Node left; 
    Node right; 
} 


int countChildren(Node head) { 
    if(head==null) return 0; 
    return countChildren(head.left)+countChildren(head.right)+ 
      ((head.left==null)?0:1) + ((head.right==null)?0:1); 
} 

我欣賞每一個建議。

+0

我們應該建議什麼? –

+0

你試過了嗎?它爲您提供了各種樹木的正確數量的孩子嗎? – RealSkeptic

+0

我建議你讓它成爲java。 – HuStmpHrrr

回答

2
public Node { 
    int data: 
    Node left; 
    Node right; 
} 


int countChildren(Node head) { 
    if(head==null) return 0; 
    return ((head.left == null) ? 0 : countChildren(head.left) + 1) + ((head.right == null) ? 0 : countChildren(head.right) + 1); 
} 

這是我的建議。