Reputation: 3
I'm trying to count number of node in specific level using recursive "Java". I tried below code but the problem is when i pass level which is not exit empty in tree for example there is 4 level in the tree when I pass 5 it keep counting element , How can I fix it ? any help appreciated .
private int countNodeLevel(int level,Node<E> n)
{
Node<E> curr=root;
if(curr == null) {
return 0;
}
if(level == 0) {
return 1;
}
return ( countNodeLevel( level - 1,n.leftChild)+countNodeLevel(level - 1, n.rightChild));
}
Upvotes: 0
Views: 727
Reputation: 109547
private int countNodeLevel(int level, Node<E> n) {
if (n == null) {
return 0;
}
if (level <= 0) {
return 0;
}
return 1
+ countNodeLevel(level - 1, n.leftChild)
+ countNodeLevel(level - 1, n.rightChild);
}
Level 0 seems more logical to return 0. For a node there is 1 + left + right.
Upvotes: 1