Java : Count even values in a Binary Search Tree recursively
I need to find out how many even values are contained in a binary tree.
this is my code.
private int countEven(BSTNode root){
开发者_如何学Python
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.
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);
}
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;
}
精彩评论