【问题标题】:Binary Search Tree Small Count Exercise二叉搜索树小计数练习
【发布时间】:2019-03-18 08:42:28
【问题描述】:

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

}

但是这是不正确的,因为您不能使用二元运算符。我将如何完成这个问题?

【问题讨论】:

  • 你能澄清一下对二元运算符的限制吗?你真的应该在没有算术、布尔或构造运算符的情况下这样做吗?甚至在没有&lt; 的情况下攻击它似乎很奇怪。
  • 我不确定,它给了我这个错误:二元运算符'的操作数类型错误
  • 是什么给了你这个错误?编译器?该错误并不是说您不能使用二元运算符'
  • 是的,它是我正在使用的编码实践网站上的编译器。我想我的错误是我需要访问节点的 VALUE,但是 node.getElement 和 node.value 不起作用。

标签: java recursion binary-tree


【解决方案1】:

是的,所以您不能只将地址与值进行比较,我认为这就是您所需要的

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 类中必须有一个属性来存储该节点的值。

【讨论】:

  • 这会命中所有节点。该问题想要达到最小数字。
  • 它给了我这个错误:找不到符号:变量值。我什至尝试过 compareTo 方法,但也没有用。
  • @Harshi 你能把 BinNode 类的结构贴在这里
  • 值,我的意思是 BinNode 类的任何值属性,它可以是 val 或 Value 或 value 等。什么不是,它可以是您为该类指定的任何值
  • @zenwraight 我不确定我是否可以这样做,这是在编码练习网站上。
【解决方案2】:

这应该可行:

public int BSTsmallcount(BinNode root, int key){
if(root == null) return 0;
if (root.value() < key)
    return 1 + BSTsmallcount(root.left(), key);
else
    return BSTsmallcount(root.left(), key);
}

更正: 1.它应该是null而不是NULL 2. 适当的递归方法只会检查其自己的基本情况。因此,没有必要检查孩子的价值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    相关资源
    最近更新 更多