简体   繁体   中英

Count leaf nodes in binary tree in Java

I have written the below code for finding the number of leaf nodes in binary tree. I submitted it on GeeksForGeeks and it is giving result as correct answer, but I am not sure whether they have checked it for large number of test cases. Could you please tell me whether it is the correct solution?

int sum=0;
int countLeaves(Node node) 
{
     // Your code
     if(node==null)
     return sum;
     if(node.left!=null || node.right!=null)
     {
         sum=countLeaves(node.left);
         sum=countLeaves(node.right);
     }
     else
     {
         sum++;
     }
     return sum;

}

Your solution does seem to produce the correct result, but it does so in a awkward way. Assigning both countLeaves(node.left) and countLeaves(node.right) to sum looks at a first glance like a bug. At a second glance, it's completely unnecessary, since sum already contains the value you are assigning to it.

If you are using an outside variable ( sum ) to count the leaves (which is usually a bad idea), there's no point in assigning the result of the recursive calls to sum .

You can simply write:

int sum=0;
int countLeaves(Node node) 
{
     if(node==null)
         return sum;
     if(node.left!=null || node.right!=null) {
         countLeaves(node.left);
         countLeaves(node.right);
     } else {
         sum++;
     }
     return sum;
}

You can even change that method to return nothing and just get the result from the sum variable after the call.

However, I suggest avoiding the sum variable, to make the code cleaner:

int countLeaves(Node node) 
{
    if (node==null)
        return 0;
    else if (node.left!=null || node.right!=null) {
        return countLeaves(node.left) + countLeaves(node.right);
    } else {
        return 1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM