views:

224

answers:

2

Hi,

I need to find out how many even values are contained in a binary tree.

this is my code.

private int countEven(BSTNode root){

if ((root == null)|| (root.value%2==1))
return 0;

return 1+ countEven(root.left) + countEven(root.right);


}

this i just coded as i do not have a way to test this out. I'm not able to test it out at the moment but need an answer so badly. any help is deeply appreciated.

A: 
private int countEven(BSTNode root) {
   if (root == null)
      return 0;

   int n = countEven(root.left) + countEven(root.right);
   if(root.value % 2 == 0)
      return n + 1;
   else
      return n;
}
Itay
Stack Overflow: where programmers will do your homework with no questions asked.
danben
hm, I don't agree with the -1... The poster tried something himself which did not work. Now he has a better solution, so he will be able to compare and see what he did wrong. So he certainly will have learned something from it...
Fortega
Yes, you could say that for every instance in which someone responds to a homework question with a fully-written solution. The flip side is that they can just copy it and learn nothing except that they can come here to get their homework done for free.
danben
I do not agree with -1 either, so +1 for you:)
pajton
No, the big difference with a normal homework question is that he tried something himself, instead of only posting the question.
Fortega
Thank you too ltay. :)
and yes. I tried to code it with my brain without testing it out. I have a test tomorrow morning and I dont want to bother writing BST class and making up a tree to test this out. infact i knew there is nothing much missing from my code. so thumbs up to Fortega and ltay. there's still some good humans left in this world.
+1  A: 

If there is an node with an odd value containing subnodes with even values, the subnodes will not be counted in your code. Small enhancement below.

private int countEven(BSTNode root){

  if (root == null)
    return 0;

  int val = (root.value%2==1) ? 0 : 1;

  return val + countEven(root.left) + countEven(root.right);


}
Fortega
Hi Thank you very much. Thanks for helping to figure out what is missing.