Java的:递归的二叉搜索树计数偶数值
-
24-09-2019 - |
题
我需要了解多少,即使值包含在二叉树。
这是我的代码。
private int countEven(BSTNode root){
if ((root == null)|| (root.value%2==1))
return 0;
return 1+ countEven(root.left) + countEven(root.right);
}
此我只编码为I没有办法来测试了这一点。我无法测试出来的时刻,但需要一个答案这么惨。 任何帮助深深地理解。
解决方案
如果存在与含有具有偶数值的子节点的奇值的节点,子节点将不会在代码计数。小的增强的下方。
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;
}
不隶属于 StackOverflow