java - 二叉搜索树小计数练习

标签 java recursion binary-tree

我正在尝试编写一个执行以下操作的方法: 给定 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/

相关文章:

在 C 中使用递归创建二叉树

java - 同步方法中的线程锁定

java - 用Java将BsonDocument写入文件

python - 不要在递归树打印机中缩进第一层树

java - 从以下树状数据结构中获取所有可能的组合

algorithm - 我应该使用什么算法来解决 "shortest path problem"?

java - Axis2生成的WSDL文件参数名称与实际名称不同

java - 如何将字符串添加到 LinkedHashSet?

c++ - 递归二叉树函数

algorithm - 无线程二叉搜索树的中序遍历,没有堆栈