当前位置: 代码迷 >> java >> 在BST中计算少于X的节点数
  详细解决方案

在BST中计算少于X的节点数

热度:38   发布时间:2023-07-27 09:41:12.0

我有一个代码可以解决这些问题。 您能否给我一些提示或指导,以说明我正在犯的错误或应该做出的任何更改? 错误是:

BSTNode'<'Golfer'>'无法转换为BinarySearchTree'<'Golfer'>'。

public int countLess (BinarySearchTree <Golfer> tree, int value) {
BSTNode<Golfer> node = tree.node;

if (node == null) 
return 0;

int left = countLess(node.getLeft(), value);
int right  = countRight(node.getRight(), value);
return (node.getInfo() > maxValue ? 1:0) + countLeft + countRight;
}

我认为应该是这样的,因为我猜到node.getLeft()实际上在BST中为您提供了一个节点,而不是完整的Left Subtree。

public int countLess (BSTNode <Golfer> node, int value) {
    if (node == null) 
         return 0;
    int left = countLess(node.getLeft(), value);
    int right  = countLess(node.getRight(), value);
    return (node.getInfo() > maxValue ? 1:0) + left + right;
}

希望这能解决您的问题。 如果可以共享BinarySearchTree的实现和BSTNode类的实现,则可以提供更正确的解决方案。

我认为您应该对BST进行有序遍历。 BST有序遍历始终为您提供按升序排列的元素。 只需在进行顺序遍历时保留一个count变量(并为每个访问的节点保持递增),然后任何节点的值都超过X,就可以“中断”。

您的count变量中的最终值将是答案。

BST:二进制搜索树

  相关解决方案