Question

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.

Was it helpful?

Solution

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);


}

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top