2017-10-26 4 views
0

私は、ツリー内の子の数を数えられるLinkedBinaryTreeクラスのメソッドに取り組んでいます。私のコードは以下の通りですが、ドライバで実行すると無限ループに陥ります。Java - LinkedBinaryTree内の子の数を調べる

public int children(BinaryTreeNode<T> node) { 
    int children = 0; 
    if(node.getLeft() != null){ 
     children = 1 + children(node); 
    } 
    else if(node.getRight() != null){ 
     children = children + 1 + children(node); 

    } 
    return children; 
} 

特に、それはStackOverflowのエラーが発生し、このラインはだ、と私はそれを超えて移動することはできません。

children = 1 + children(node); 

誰もが任意のアイデアを持っている私は私のコードを修正助けるためにどのように?私の論理で見落とされているものは何ですか?ヘルプをよろしくお願いいたします。

+0

、それはそれぞれ '' node.getLeft() 'と' node.getRight()でなければなりません。 –

答えて

1

メソッドを再帰的に呼び出すときにnode-> leftまたはnode-> rightを渡す必要があります。修正されたコード:あなたの再帰呼び出しで同じノードを渡している

public int children(BinaryTreeNode<T> node) { 
int children = 0; 
if(node.getLeft() != null){ 
    children = 1 + children(node.getLeft()); 
} 
else if(node.getRight() != null){ 
    children = children + 1 + children(node.getRight()); 

} 
return children; 

}

1
public int children(BinaryTreeNode<T> node) { 
    if (node == null) 
     return 0; 
    return 1 + children(node.left()) + children(node.right()); 
} 
関連する問題