我正在尝试编写一个执行以下操作的方法: 给定 BST,编写一个递归函数 BSTsmallcount,在给定键值的情况下,返回值小于该键的节点数。您的函数应该访问 BST 中尽可能少的节点。
这就是我所拥有的:
public int BSTsmallcount(BinNode root, int key)
{
int count = 0;
if (root.right < key)
{
count += BSTsmallcount(root.left, key);
}
if (root.left < key)
{
count += BSTsmallcount(root.right, key);
}
return count;
}
但是这是不正确的,因为您不能使用二元运算符。我该如何完成这个问题?
最佳答案
是的,所以你不能只将地址与值进行比较,我认为这就是你所需要的
public int BSTsmallcount(BinNode root, int key)
{
if(root == NULL) return 0;
if (root.left.value < key)
return 1 + BSTsmallcount(root.left, key);
else
return BSTsmallcount(root.left, key);
if (root.right.value < key)
return 1 + BSTsmallcount(root.right, key);
else
return BSTsmallcount(root.right, key);
}
BinNode 类中必须有一个属性来存储该节点的值。
关于java - 二叉搜索树小计数练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43792841/